SocketM
SocketM

Reputation: 574

javax.naming.NameNotFoundException: on WebSphere Liberty

I'm trying to use a datasource configurated as a JNDI on a WebSphere Application Server Liberty however I'm getting the follwoing error:

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

The configuration for the datasource in Websphere application server is:

<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>

The connection to database is made via this code inside a 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() );    

What am I doing wrong?

Upvotes: 1

Views: 3938

Answers (2)

Gas
Gas

Reputation: 18050

The java:comp/env requires resource reference. You have following options to solve that:

1) Use resource injection - so instead of looking up it directly (via InitialContext) just add the following in your servlet class

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

2) Define resource reference in your web.xml like

<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>

or you can create just reference also via annotation in the code.

3) Use direct JNDI, without reference (not a Java EE best practice)

 DataSource ds = (DataSource) initCtx.lookup("jdbc/myapp/master");

Upvotes: 4

njr
njr

Reputation: 3484

In addition to what is already stated in the other answer, you should also check that you have enabled the jndi-1.0 feature. This is a common cause of lookups not working in Liberty.

For example, in server.xml,

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

And if this, too, is not enough to get it working, you should also check the configuration of resources upon which the dataSource depends, such as the jdbcDriver with id of ojdbc7 which is referenced in the config snippet that you provided.

Upvotes: 2

Related Questions