user manual

Chapter 22: Using JDBC 243
Connecting to JDBC Resources from Application Components
Let's look at an example entity bean that uses the Oracle datasource we
defined above:
<entity>
<ejb-name>entity_bean</ejb-name>
...
<resource-ref>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<jndi-name>serial://datasources/Oracle</jndi-name>
<cmp-resource>True</cmp-resource>
</resource-ref>
...
</entity>
As you can see, we used the identical JNDI name from the <visitransact-
datasource> element from the datasource definition. Now let's see how we
obtain a datasource object reference. To do so, the application performs a
lookup of the <res-ref-name> value of the deployed components and the object
references are retrieved from the remote JNDI Serial Context service provider.
For example:
javax.sql.DataSource ds1;
try {
javax.naming.Context ctx = (javax.naming.Context) new
javax.naming.InitialContext();
ds1 = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDataSource");
}
catch (javax.naming.NamingException exp) {
exp.printStackTrace();
}
A database java.sql.Connection can now be obtained from ds1.