Using C3P0 and Hibernate 3
C3P0 is a database connection pooling software that works very well with Hibernate. Unfortunately the documentation to get it working correctly is sparse.
What is a connection pool?
Ripped from Wikipedia:
In software engineering, a connection pool is a cache of database connections maintained by the database so that the connections can be reused when the database receives future requests for data. Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.
I will be explaining how to do this using JPA and the persistence.xml file which uses a slightly different syntax than the hibernate.cfg.xml file.
The following is a persistence.xml file that is setup to use MySQL as its database:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="mypersistenceunitname"> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.hbm2ddl.auto" value="create-drop" /> <!-- Important --> <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" /> <property name="hibernate.c3p0.max_size" value="100" /> <property name="hibernate.c3p0.min_size" value="0" /> <property name="hibernate.c3p0.acquire_increment" value="1" /> <property name="hibernate.c3p0.idle_test_period" value="300" /> <property name="hibernate.c3p0.max_statements" value="0" /> <property name="hibernate.c3p0.timeout" value="100" /> </properties> </persistence-unit> </persistence>
As you can see there is a lot of references to C3P0 in there. The most important property is the hibernate.connection.provider_class property. This property tells Hibernate that it wants to use C3P0 as its connection provider. The other references to C3P0 allow for fine tuning of how the connection pool behaves.
Other connection pools can be used in place of C3P0. Another common connection pool is DBCP.
For more information on how to configure a database connection pool for Hibernate check out:
Although most of the information is regarding Hibernate 2. The comments are helpful for Hibernate 3.