Last Updated on 17 July 2019   |   Print Email
In this tutorial, you will learn how to configure c3p0 - a popular database connection library for Java multi-threaded database applications - in a Hibernate/JPA project.Hibernate has built-in connection pool but it is not for production use, as state in official Hibernate document and also in the logging information when you start a Hibernate application:So it is recommended to use a third-party library like c3p0which is a database connection pooling library for production use, and Hibernate works very well with c3p0.Basically, it’s simple and easy to add database connection pooling capability to your existing project with c3p0: just add c3p0 dependency to the project’s Maven pom.xml file and specify some properties in Hibernate/JPA configuration file.
1. Add c3p0 dependency to Maven pom.xml file
The first step to use c3p0 is to add its dependency to your project’s pom.xml file, with the following XML code:
You can see this dependency is provided by Hibernate. Note that the version should be compatible with Hibernate version you are using in your project. Save the file, and you can see there are 3 JAR files have been added to the project:
That means if you don’t use Maven, you can find, download and add these JAR files to your project.
2. Configure c3p0 properties with Hibernate
c3p0 offers various configuration properties, but basically you need to use the following ones:
hibernate.c3p0.min_size: the minimum number of connections maintained in the pool at any given time.
hibernate.c3p0.max_size: the maximum number of connections maintained in the pool at any given time.
hibernate.c3p0.timeout: the number of seconds an idle connection is kept in the pool. If a connection is idle longer than this timeout value, then it will be replaced by a new one.
hibernate.c3p0.max_statements: the total number of Statements cached for all connections.
To see the complete list of configuration properties in c3p0, see Configuration Properties.Then your Hibernate configuration file (hibernate.cfg.xml) would look like this:
You can look at the Hibernate’s log to check if c3p0 is initialized and running, as shown in the following screenshot: If you use MySQL Workbench, click Server > Client Connections and you can see there are some sleep connections to your database:That’s how to configure c3p0 database connection pooling library with Hibernate/JPA.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
Can I use this configuration for hibernate without jpa application?
Thanks