有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javajavax。命名。NameNotFoundException:关于WebSphere Liberty

我试图在WebSphere Application Server Liberty上使用配置为JNDI的数据源,但是我得到了以下错误:

javax.naming.NameNotFoundException: java:comp/env/jdbc/myapp/master

Websphere application server中数据源的配置为:

<dataSource commitOrRollbackOnCleanup="commit" id="jdbc/myapp/master" jdbcDriverRef="ojdbc7" jndiName="jdbc/myapp/master">
        <properties.oracle URL="jdbc:oracle:thin:@127.0.0.1:1521:xe" oracleRACXARecoveryDelay="0" password="xxxxxxxx" user="app_master"> 
         </properties.oracle>
         <connectionManager maxPoolSize="50"/>
    </dataSource>

通过servlet(jndi=jdbc/myapp/master)中的以下代码连接到数据库:

Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup(jndi);
            setConnection(ds.getConnection());
            System.out.println(getConnection().toString() );    

我做错了什么


共 (2) 个答案

  1. # 1 楼答案

    java:comp/env需要资源引用。您有以下选项来解决这个问题:

    1)使用资源注入——所以不要直接(通过InitialContext)查找它,只需在servlet类中添加以下内容

    @Resource(lookup = "jdbc/myapp/master", name="jdbc/myapp/master")
    private DataSource dataSource;
    

    2)在web.xml类中定义资源引用

    <resource-ref>
       <description>my datasource</description>
       <res-ref-name>jdbc/myapp/master</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>CONTAINER</res-auth>
    </resource-ref>
    

    或者也可以通过代码中的注释创建引用

    3)使用直接JNDI,无需参考(不是Java EE最佳实践)

     DataSource ds = (DataSource) initCtx.lookup("jdbc/myapp/master");
    
  2. # 2 楼答案

    除了在另一个答案中已经说明的内容外,您还应该检查是否启用了jndi-1.0功能。这是导致查找无法在Liberty中运行的常见原因

    例如,在服务器中。xml

    <featureManager>
      <feature>jdbc-4.2</feature>
      <feature>jndi-1.0</feature>
      ... other features that you use
    </featureManager>
    

    如果这还不足以让它工作,那么还应该检查数据源所依赖的资源的配置,比如id为ojdbc7的jdbcDriver,它在您提供的配置代码段中被引用