1

我正在尝试在 WebSphere Application Server Liberty 上使用配置为 JNDI 的数据源,但是出现以下错误:

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

Websphere 应用服务器中数据源的配置为:

<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() );    

我究竟做错了什么?

4

2 回答 2

4

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

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

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

web.xml2)在你喜欢的定义资源引用

<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");
于 2019-03-05T12:52:30.080 回答
1

除了其他答案中已经说明的内容外,您还应该检查是否启用了 jndi-1.0 功能。这是查找在 Liberty 中不起作用的常见原因。

例如,在 server.xml 中,

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

如果这也不足以使其正常工作,您还应该检查 dataSource 所依赖的资源的配置,例如您提供的配置片段中引用的 id 为 ojdbc7 的 jdbcDriver。

于 2019-03-05T14:15:26.863 回答