Sunday, February 04, 2007

Configure MySQL JDBC Datasource in Tomcat 5.5

Found the instructions posted on Tomcat JNDI Datasource HOW-TO does not work for me. The datasource initialized does not have any reference to the parameters confgured through ResourceParams element.

After searching through vast amount of posts on TheServerSide I found these steps to be the simplest ones.

1. Make sure MySQL JDBC driver jar file such as "mysql-connector-java-3.1.14-bin.jar" is in the /commom/lib directory. The Connector/J version 5.0 does not work with Tomcat 5.5 connection pool.

There should be no other version of the MySQL JDBC driver in neither this directory not WEB-INF/lib directory.

2. Update the web application context definition in $TOMCAT_HOME/conf/server.xml

<Context path="/testApp" reloadable="true" docBase="D:\testApp\webapp" workDir="D:\testApp\work">

<Resource name="jdbc/MySQLDB"
auth="Container"
type="javax.sql.DataSource"
username="dbuser"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/testDB"
maxActive="20"
maxIdle="5"
validationQuery="SELECT 1"
testOnBorrow="true"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="60000"/>
</Context>

Do not include the FACTORY attribute as instructed as JNDI Datasource HOW-TO, this is automatically picked up by tomcat 5.5 based on the type of datasource, which here is java.sql.Datasource. Therefore it automatically uses the Tomcat internal dbcp factory.

3. Restart the Tomcat, that's it.

4. Now in your code you should be able to look the connection pool like this:

Context initContext = new InitialContext();
DataSource ds = (DataSource)envContext.lookup("java:/comp/env/jdbc/MySQLDB");
Connection conn = ds.getConnection();
....

Labels: