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?
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");