You need to define a resource reference in your application and then map that logical resource reference to the physical resource (data source) during deployment.
In your web.xml
, add the following configuration (modifying the names and properties as appropriate):
<resource-ref>
<description>Resource reference to my database</description>
<res-ref-name>jdbc/MyDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Then, during application deployment, WAS will prompt you to map this resource reference (jdbc/MyDB
) to the data source you created in WAS.
In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (res-ref-name
), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (java:comp/env/
).
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");