Tuesday, August 11, 2009

Converting an application using an internal datasource to one using a JNDI datasource

Elaboration for Tomcat 6 and Oracle 10; other application or db servers are similar.

1. Copy the jdbc driver jar (ojdbc14.jar) to $TOMCAT_HOME/lib

2. To the application's context.xml, add the following lines:

<Resource name="jdbc/XXX"
auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="url" username="usr" password="pass"
removeAbandoned="true" maxActive="-1" maxIdle="-1" maxWait="-1"/>

where XXX is the name the datasource will take in the JNDI tree, and url, username and password keep the real values used before.
The other parameters may be finetuned at will. removeAbandoned="true" makes sure that that abandoned dB connections are removed and recycled.

3. To the application's web.xml, add the following:

<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/XXX</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

where XXX matches the JNDI name chosen before.

4. Within the application, use the datasource's JNDI name when referring to it: java:comp/env/jdbc/XXX
for instance, in Spring's applicationContext.xml, one can add:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/XXX"/>
</bean>

and inject this bean in other beans that need a datasource.

5. Since the Oracle driver will already be loaded by Tomcat's classloader at the startup of the application, it isn't needed to deploy it with the application, it's only needed to compile. Hence, in Eclipse, in the project's properties->Java EE Module Dependencies, unmark the dependency on the oracle driver (ojdbc14.jar), or remove it from the dist target within a custom Ant script.

Source: http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

No comments: