Saturday, October 8, 2011

How to configure MySQL DataSource in Tomcat 6


1. Get MySQL JDBC Driver
Get JDBC driver here – http://www.mysql.com/products/connector/ , for example, mysql-connector-java-5.1.9.jar, and copy it to $TOMCAT\lib folder.
2. Create META-INF/context.xml
Add a file META-INF/context.xml into the root of your web application folder, which defines database connection detail :
File : META-INF/context.xml
<Context>

  <Resource name="jdbc/bestjavapractices " auth="Container" type="javax.sql.DataSource"
               maxActive="50" maxIdle="30" maxWait="10000"
               username="mysqluser" password="mysqlpassword"
               driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/bestjavapractices"/>

</Context>
3. web.xml configuration
In web.xml, defines your MySQL datasource again :
  <resource-ref>
        <description>MySQL Datasource example</description>
        <res-ref-name>jdbc/bestjavapractices </res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
  </resource-ref>
See a full web.xml example below :
File : web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">

  <display-name>MySQL DataSource Example</display-name>

  <resource-ref>
        <description>MySQL Datasource example</description>
        <res-ref-name>jdbc/bestjavapractices </res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
  </resource-ref>

</web-app>
4. Run It
Resource injection (@Resource) is the easiest way to get the datasource from Tomcat, see below :
import javax.annotation.Resource;
public class CustomerBean{

        @Resource(name="jdbc/bestjavapractices ")
        private DataSource ds;

        public List<Customer> getCustomerList() throws SQLException{

          //get database connection
          Connection con = ds.getConnection();
          //...
Alternatively, you can also get the datasource via context lookup service :
import javax.naming.Context;
import javax.naming.InitialContext;
public class CustomerBean{

        private DataSource ds;

        public CustomerBean(){
          try {
               Context ctx = new InitialContext();
               ds = (DataSource)ctx.lookup("java:comp/env/jdbc/bestjavapractices ");
          } catch (NamingException e) {
               e.printStackTrace();
          }
        }

        public List<Customer> getCustomerList() throws SQLException{

          //get database connection
          Connection con = ds.getConnection();
          //...
Reference
  1. Tomcat 6 : JNDI Datasource HOW-TO

No comments: