Configure Tomcat JDBC Connection Pool (DataSource) 

Joined:
04/09/2007
Posts:
776

February 01, 2011 14:36:04    Last update: February 01, 2011 14:37:09
Tomcat JDBC connection pool can be configured with META-INF/context.xml. This is the example given in the Tomcat doc:
<Context>
    <Resource name="jdbc/EmployeeDB"
	      auth="Container"
              type="javax.sql.DataSource"
              username="dbusername"
              password="dbpassword"
              driverClassName="org.hsql.jdbcDriver"
              url="jdbc:HypersonicSQL:database"
              maxActive="8"
              maxIdle="4"/>
</Context>


To use the DataSource in your Java code:
Context initCtx = new InitialContext();
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/EmployeeDB");
Connection conn = ds.getConnection();
// ... use this connection to access the database ...
conn.close();


In contrast to Tomcat documentation, there's no need to declare resource-ref in web.xml.

The above example uses Tomcat's standard DataSource resource factory: org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory. If you are using a third party DataSource factory, the configuration may be different. For example, if you are using HA-JDBC, context.xml may look like:
<Context>
  <!-- ... -->
  <Resource name="jdbc/cluster" 
	    type="javax.sql.DataSource"
            username="postgres" 
	    password="password" 
	    driverClassName="net.sf.hajdbc.sql.Driver"
            url="jdbc:ha-jdbc:cluster1"/>
  <!-- ... -->
</Context>

Share |
| Comment  | Tags