Connection Pool DBCP

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database JDBC Connection Pool » Connection Pool DBCP 
DBCP Database connection pooling services
License:Apache License
URL:http://commons.apache.org/dbcp/
Description:Database connection pooling services.
Package NameComment
org.apache.commons.dbcp Package Documentation for org.apache.commons.dbcp

Database Connection Pool API.

Overview in Dialog Form

Q: How do I use the DBCP package?

A: There are two primary ways to access the DBCP pool, as a {@link java.sql.Driver Driver}, or as a {@link javax.sql.DataSource DataSource}. You'll want to create an instance of {@link org.apache.commons.dbcp.PoolingDriver} or {@link org.apache.commons.dbcp.PoolingDataSource}. When using one of these interfaces, you can just use your JDBC objects the way you normally would. Closing a {@link java.sql.Connection} will simply return it to its pool.

Q: But {@link org.apache.commons.dbcp.PoolingDriver PoolingDriver} and {@link org.apache.commons.dbcp.PoolingDataSource PoolingDataSource} both expect an {@link org.apache.commons.pool.ObjectPool ObjectPool} as an input. Where do I get one of those?

A: The {@link org.apache.commons.pool.ObjectPool ObjectPool} interface is defined in the {@link org.apache.commons.pool} package (Commons-Pool). The {@link org.apache.commons.pool.impl} package has a couple of implementations, and you can always create your own.

Q: Ok, I've found an {@link org.apache.commons.pool.ObjectPool ObjectPool} implementation that I think suits my connection pooling needs. But it wants a {@link org.apache.commons.pool.PoolableObjectFactory PoolableObjectFactory}. What should I use for that?

A: The DBCP package provides a class for this purpose. It's called {@link org.apache.commons.dbcp.PoolableConnectionFactory}. It implements the factory and lifecycle methods of {@link org.apache.commons.pool.PoolableObjectFactory} for {@link java.sql.Connection}s. But it doesn't create the actual database {@link java.sql.Connection}s itself, if uses a {@link org.apache.commons.dbcp.ConnectionFactory} for that. The {@link org.apache.commons.dbcp.PoolableConnectionFactory} will take {@link java.sql.Connection}s created by the {@link org.apache.commons.dbcp.ConnectionFactory} and wrap them with classes that implement the pooling behaviour.

Several implementations of {@link org.apache.commons.dbcp.ConnectionFactory} are provided--one that uses {@link java.sql.DriverManager} to create connections ({@link org.apache.commons.dbcp.DriverManagerConnectionFactory}), one that uses a {@link java.sql.Driver} to create connections ({@link org.apache.commons.dbcp.DriverConnectionFactory}), one that uses a {@link javax.sql.DataSource} to create connections ({@link org.apache.commons.dbcp.DataSourceConnectionFactory}).

Q: I think I'm starting to get it, but can you walk me though it again?

A: Sure. Let's assume you want to create a {@link javax.sql.DataSource} that pools {@link java.sql.Connection}s. Let's also assume that that those pooled {@link java.sql.Connection}s should be obtained from the {@link java.sql.DriverManager}. You'll want to create a {@link org.apache.commons.dbcp.PoolingDataSource}.

The {@link org.apache.commons.dbcp.PoolingDataSource} uses an underlying {@link org.apache.commons.pool.ObjectPool} to create and store its {@link java.sql.Connection}.

To create a {@link org.apache.commons.pool.ObjectPool}, you'll need a {@link org.apache.commons.pool.PoolableObjectFactory} that creates the actual {@link java.sql.Connection}s. That's what {@link org.apache.commons.dbcp.PoolableConnectionFactory} is for.

To create the {@link org.apache.commons.dbcp.PoolableConnectionFactory}, you'll need at least two things:

  1. A {@link org.apache.commons.dbcp.ConnectionFactory} from which the actual database {@link java.sql.Connection}s will be obtained.
  2. An empty and factory-less {@link org.apache.commons.pool.ObjectPool} in which the {@link java.sql.Connection}s will be stored.
    When you pass an {@link org.apache.commons.pool.ObjectPool} into the {@link org.apache.commons.dbcp.PoolableConnectionFactory}, it will automatically register itself as the {@link org.apache.commons.pool.PoolableObjectFactory} for that pool.
You can optionally provide a {@link org.apache.commons.pool.KeyedObjectPoolFactory} that will be used to create {@link org.apache.commons.pool.KeyedObjectPool}s for pooling {@link java.sql.PreparedStatement}s for each {@link java.sql.Connection}.

In code, that might look like this:

GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string", "username", "password");
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

To create a {@link org.apache.commons.dbcp.PoolingDriver}, we do the same thing, except that instead of creating a {@link javax.sql.DataSource} on the last line, we create a {@link org.apache.commons.dbcp.PoolingDriver}, and register the connectionPool with it. E.g.,:

GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string", "username", "password");
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
PoolingDriver driver = new PoolingDriver();
driver.registerPool("example",connectionPool);

Since the {@link org.apache.commons.dbcp.PoolingDriver} registers itself with the {@link java.sql.DriverManager} when it is created, now you can just go to the {@link java.sql.DriverManager} to create your {@link java.sql.Connection}s, like you normally would:

Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example");

Q: Sounds complicated, is there an easier way?

A: If you're using the {@link org.apache.commons.dbcp.PoolingDriver}, you don't need to do this configuration in code. Instead, you can provide a JOCL document that describes the connection pool, and let the {@link org.apache.commons.dbcp.PoolingDriver} discover it at runtime.

Specifically, if the {@link org.apache.commons.dbcp.PoolingDriver} is asked for a {@link java.sql.Connection} from a pool that has not yet been registered, it will look for a named resource from which to read the pool's configuration, and create that pool.

For example, suppose you create a pool named "/eg" from a JOCL document. The "connect string" for this pool will be "jdbc:apache:commons:dbcp:/eg". To do this, you'll need a create a resource (just a file in your classpath) containing a JOCL description of the pool. Specifically, this JOCL document should define a {@link org.apache.commons.dbcp.PoolableConnectionFactory} from which the pool will be obtained. For example:

<object class="org.apache.commons.dbcp.PoolableConnectionFactory" xmlns="http://apache.org/xml/xmlns/jakarta/commons/jocl">
   <!-- the first argument is the ConnectionFactory -->
   <object class="org.apache.commons.dbcp.DriverManagerConnectionFactory">
      <string value="jdbc:some:connect:string"/>
      <object class="java.util.Properties" null="true"/>
   </object>
   <!-- the next argument is the ObjectPool -->
   <object class="org.apache.commons.pool.impl.GenericObjectPool">
      <object class="org.apache.commons.pool.PoolableObjectFactory" null="true"/>
      <int value="10"/> <!-- max active -->
      <byte value="1"/> <!-- when exhausted action, 0 = fail, 1 = block, 2 = grow -->
      <long value="2000"/> <!-- max wait -->
      <int value="10"/> <!-- max idle -->
      <boolean value="false"/> <!-- test on borrow -->
      <boolean value="false"/> <!-- test on return -->
      <long value="10000"/> <!-- time between eviction runs -->
      <int value="5"/> <!-- number of connections to test per eviction run -->
      <long value="5000"/> <!-- min evictable idle time -->
      <boolean value="true"/> <!-- test while idle -->
   </object>
   <!-- the next argument is the KeyedObjectPoolFactory -->
   <object class="org.apache.commons.pool.impl.StackKeyedObjectPoolFactory">
      <int value="5"/> <!-- max idle -->
   </object>
   <string value="SELECT COUNT(*) FROM DUAL"/> <!-- validation query -->
   <boolean value="false"/> <!-- default read only -->
   <boolean value="true"/> <!-- default auto commit -->
</object>

Simply save that file somewhere in your classpath as eg.jocl, and the {@link org.apache.commons.dbcp.PoolingDriver} will find it automatically. You need only register the {@link org.apache.commons.dbcp.PoolingDriver} (for example, using the jdbc.drivers property), and use the the {@link java.sql.DriverManager} to create your {@link java.sql.Connection}s, like you normally would:

Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:/eg");

(Note that without the leading slash, the pool must be located at org/apache/commons/dbcp/PoolingDriver/eg.jocl within your classpath. See {@link java.lang.Class#getResource} for details.)

org.apache.commons.dbcp.cpdsadapter

This package contains one public class which is a ConnectionPoolDataSource (CPDS) implementation that can be used to adapt older Driver based jdbc implementations. Below is an example of setting up the CPDS to be available via JNDI in the catalina servlet container.

In server.xml, the following would be added to the <Context> for your webapp:

 <Resource name="jdbc/bookstoreCPDS" auth="Container"
            type="org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS"/>
  <ResourceParams name="jdbc/bookstoreCPDS">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS</value>
    </parameter>
        <parameter><name>user</name><value>root</value></parameter>
        <parameter><name>password</name><value></value></parameter>
        <parameter>
            <name>driver</name>
            <value>org.gjt.mm.mysql.Driver</value></parameter>
        <parameter>
             <name>url</name>
             <value>jdbc:mysql://localhost:3306/bookstore</value>
        </parameter>
  </ResourceParams>

In web.xml. Note that elements must be given in the order of the dtd described in the servlet specification:

<resource-ref>
  <description>
    Resource reference to a factory for java.sql.Connection
    instances that may be used for talking to a particular
    database that is configured in the server.xml file.
  </description>
  <res-ref-name>
    jdbc/bookstoreCPDS
  </res-ref-name>
  <res-type>
    org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>

Catalina deploys all objects configured similarly to above within the java:comp/env namespace.

org.apache.commons.dbcp.datasources

This package contains two DataSources: PerUserPoolDataSource and SharedPoolDataSource which provide a database connection pool. Below are a couple of usage examples. One shows deployment into a JNDI system. The other is a simple example initializing the pool using standard java code.

JNDI

Most J2EE containers will provide some way of deploying resources into JNDI. The method will vary among containers, but once the resource is available via JNDI, the application can access the resource in a container independent manner. The following example shows deployment into tomcat (catalina).

In server.xml, the following would be added to the <Context> for your webapp:


 <Resource name="jdbc/bookstore" auth="Container"
            type="org.apache.commons.dbcp.datasources.PerUserPoolPoolDataSource"/>
  <ResourceParams name="jdbc/bookstore">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory</value>
    </parameter>
    <parameter>
      <name>dataSourceName</name><value>java:comp/env/jdbc/bookstoreCPDS</value>
    </parameter>
    <parameter>
      <name>defaultMaxActive</name><value>30</value>
    </parameter>

  </ResourceParams>

In web.xml. Note that elements must be given in the order of the dtd described in the servlet specification:

<resource-ref>
  <description>
    Resource reference to a factory for java.sql.Connection
    instances that may be used for talking to a particular
    database that is configured in the server.xml file.
  </description>
  <res-ref-name>
    jdbc/bookstore
  </res-ref-name>
  <res-type>
    org.apache.commons.dbcp.datasources.PerUserPoolDataSource
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>

Catalina deploys all objects configured similarly to above within the java:comp/env namespace. So the JNDI path given for the dataSourceName parameter is valid for a ConnectionPoolDataSource that is deployed as given in the cpdsadapter example

The DataSource is now available to the application as shown below:


    Context ctx = new InitialContext();                
    DataSource ds = (DataSource)
        ctx.lookup("java:comp/env/jdbc/bookstore");
    Connection con = null;
    try
    {
        con = ds.getConnection();
        ... 
        use the connection
        ...
    }
    finally
    {
        if (con != null)
            con.close();
    }

The reference to the DataSource could be maintained, for multiple getConnection() requests. Or the DataSource can be looked up in different parts of the application code. PerUserPoolDataSourceFactory and SharedPoolDataSourceFactory will maintain the state of the pool between different lookups. This behavior may be different in other implementations.

Without JNDI

Connection pooling is useful in applications regardless of whether they run in a J2EE environment and a DataSource can be used within a simpler environment. The example below shows SharedPoolDataSource using DriverAdapterCPDS as the backend source, though any CPDS is applicable.


public class Pool
{
    private static DataSource ds;

    static
    {
        DriverAdapterCPDS cpds = new DriverAdapterCPDS();
        cpds.setDriver("org.gjt.mm.mysql.Driver");
        cpds.setUrl("jdbc:mysql://localhost:3306/bookstore");
        cpds.setUser("foo");
        cpds.setPassword(null);

        SharedPoolDataSource tds = new SharedPoolDataSource();
        tds.setConnectionPoolDataSource(cpds);
        tds.setMaxActive(10);
        tds.setMaxWait(50);

        ds = tds;
    }

    public static getConnection()
    {
        return ds.getConnection();
    }  
}

This class can then be used wherever a connection is needed:

    Connection con = null;
    try
    {
        con = Pool.getConnection();
        ... 
        use the connection
        ...
    }
    finally
    {
        if (con != null)
            con.close();
    }
org.apache.commons.jocl Package Documentation for org.apache.commons.jocl

Java Object Configuration Language, an XML application for describing Java Objects to be instantiated. See {@link org.apache.commons.jocl.JOCLContentHandler}.

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.