hibernate

Hibernate Connection Pool configuration with C3P0 Example

This is a tutorial on how to use C3P0 connection pool framework 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

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sergio Prado
Sergio Prado
6 years ago

Muito grato!!!! Você me salvou…

Pallavi Asabe
Pallavi Asabe
4 years ago

Is is work for oracle database with jdbc.driver.OracleDriver?

Back to top button