Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Hibernate Connection Pool configuration with C3P0 Example

This is a tutorial on how to use C3P0 connection pool framwork with Hibernate. Basically what a connection pool does is to create a number of connections (a pool of connections) with the database server and keep them idle. Every time a query comes up the application picks one of the pooled connections and uses that to interact with the database. Connection pools substantialy help performance because your application doesn’t have to create a new connection to the database server every time a query is submited.

It can use one of the already established ones from the connection pool. Additionally if your already established connections are not enough, it can automatically create more connections to satisfy as much requests as possible. Hibernate has a connection pooling mechanism as standard, but it’s not very useful for production use and for applications that have to deal with freqeunt and time consuming database interaction.

So these are the tools we are going to use on a Windows 7 platform:

  • JDK 1.7
  • Maven 3.0.5
  • Hibernate 4.2.3.Final
  • MySQL JDBC driver 5.1.9
  • Eclipse 4.3 Kepler
  • hibernate-c3p0.4.2.3.Final

The basis of this tutorials is going to be this Eclipse project: HibernateMySQLExample.zip. And it’s based in Hibernate 3 with Maven 2 and MySQL 5 Example (XML Mapping and Annotation)

Hibernate with C3P0

Remember that the basic structure of our program is this:

project_struvture

1. Download C3P0

In order to integrate c3p0 with Hibernate you have to put hibernate-c3p0.jar to your CLASSPATH. So go ahead and declare the following dependencies to pom.xml file of the project.

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks</groupId>
	<artifactId>HibernateMySQLExample</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>HibernateMySQLExample</name>
	<url>http://maven.apache.org</url>

	<!-- JBoss repository for Hibernate -->

	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
		</repository>
	</repositories>

	<dependencies>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.3.Final</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency> 

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>4.2.3.Final</version>
		</dependency>

	</dependencies>

</project>

2. C3P0 configuration

You have to configure the basic parameters of the connection pool in hibernate.cfg.xml file of your project:

hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorials</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>

		<property name="hibernate.
connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<property name="hibernate.c3p0.min_size">7</property>
		<property name="hibernate.c3p0.max_size">53</property>
		<property name="hibernate.c3p0.timeout">100</property>
		<property name="hibernate.c3p0.max_statements">50</property>
		<property name="hibernate.c3p0.idle_test_period">1000</property>
		<property name="hibernate.c3p0.validate">true</property>
		<property name="hibernate.connection.provider_class">org.hibernate.service.
jdbc.connections.internal.C3P0ConnectionProvider</property>

		<mapping resource="com/javacodegeeks/Student.hbm.xml"></mapping>
	</session-factory>
</hibernate-configuration>

These are the basic things you need to know about c3p0 configuration properties:

  • minPoolSize: Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 1. It is the minimun number of connections that your pool is going to create and hold.
  • maxPoolSize: Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 100. It’s the maximum number of connections that are going to be created.
  • idleTestPeriod: Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0. If this is a number greater than 0, c3p0 will test all idle, pooled but unchecked-out connections, every this number of seconds.
  • timeout: Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0. The seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire.
  • maxStatements: Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0. The size of c3p0′s PreparedStatement cache. Zero means statement caching is turned off.

For more information on Hibernate Configurations, check out Hibernate C3P0 wiki page.

In our basic Project the App.java file simply creates a Student instance and persists it to the database. The thing is that when JVM exits, the pool connection is going to be destroyed. So,in order to check that our pool connections remains up while the programm is running we are going to put some latency in App.java.

App.java:

package com.javacodegeeks;

import org.hibernate.Session;

import com.javacodegeeks.utils.HibernateUtil;

public class App 
{
    public static void main( String[] args )
    {

        Session session = HibernateUtil.getSessionFactory().openSession(); 
        session.beginTransaction();

        Student student = new Student();

        student.setStudentName("JavaFun");
        student.setStudentAge("19");

        try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        session.getTransaction().commit();

        System.out.println("Great! Student was saved");
    }
}

Now when you run the program you can confirm that 7 connections are going to be created and kept in the connection pool:

connections-workbench

This was an example on Hibernate Cnnection Pool configuration with C3P0. Download the Eclipse project of this example: HibernateC3P0.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books