Hibernate with C3PO connection pool

Please Check Connection Pool Overview article to understand the basics of Connectiool

Let us understand Hibernate with C3PO connection pool

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Step 2

Update pom.xml with Hibernate and connection pool provider dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.  
  5.     <groupId>HibernateConnectionPool</groupId>
  6.     <artifactId>HibernateConnectionPool</artifactId>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <packaging>jar</packaging>
  9.  
  10.     <name>HibernateConnectionPool</name>
  11.     <url>http://maven.apache.org</url>
  12.  
  13.     <properties>
  14.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.     </properties>
  16.  
  17.     <dependencies>
  18.         <dependency>
  19.             <groupId>junit</groupId>
  20.             <artifactId>junit</artifactId>
  21.             <version>3.8.1</version>
  22.             <scope>test</scope>
  23.         </dependency>
  24.         <dependency>
  25.             <groupId>org.hibernate</groupId>
  26.             <artifactId>hibernate-core</artifactId>
  27.             <version>5.2.6.Final</version>
  28.         </dependency>
  29.         <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
  30.         <dependency>
  31.             <groupId>org.hibernate</groupId>
  32.             <artifactId>hibernate-c3p0</artifactId>
  33.             <version>5.2.8.Final</version>
  34.         </dependency>
  35.  
  36.  
  37.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  38.         <dependency>
  39.             <groupId>mysql</groupId>
  40.             <artifactId>mysql-connector-java</artifactId>
  41.             <version>6.0.5</version>
  42.         </dependency>
  43.     </dependencies>
  44. </project>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>HibernateConnectionPool</groupId>
	<artifactId>HibernateConnectionPool</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>HibernateConnectionPool</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>5.2.8.Final</version>
		</dependency>


		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
	</dependencies>
</project>

Step 3

Create Employee class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name = "Employee")
  12. public class Employee {
  13.     @Id
  14.     @GeneratedValue(strategy = GenerationType.AUTO)
  15.     @Column(name = "id")
  16.     private int id;
  17.    
  18.     @Column(name = "name")
  19.     private String name;
  20.    
  21.     @Column(name="city")
  22.     private String city;
  23.  
  24.     public int getId() {
  25.         return id;
  26.     }
  27.  
  28.     public void setId(int id) {
  29.         this.id = id;
  30.     }
  31.  
  32.     public String getName() {
  33.         return name;
  34.     }
  35.  
  36.     public void setName(String name) {
  37.         this.name = name;
  38.     }
  39.    
  40.     public String getCity() {
  41.         return city;
  42.     }
  43.  
  44.     public void setCity(String city) {
  45.         this.city = city;
  46.     }
  47. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;
	
	@Column(name = "name")
	private String name;
	
	@Column(name="city")
	private String city;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}
}

Step 4

Create hibernate.cfg.xml

We have defined all the connection pool configuration

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.     <session-factory>
  9.  
  10.         <!-- Database connection properties -->
  11.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.         <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.         <property name="connection.username">root</property>
  14.         <property name="connection.password">root</property>
  15.  
  16.         <property name="hibernate.c3p0.min_size">5</property>
  17.         <property name="hibernate.c3p0.max_size">30</property>
  18.         <property name="hibernate.c3p0.timeout">120</property>
  19.         <property name="hibernate.c3p0.max_statements">50</property>
  20.         <property name="hibernate.c3p0.idle_test_period">2000</property>
  21.  
  22.         <!-- SQL dialect -->
  23.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  24.  
  25.         <!-- Disable the second-level cache -->
  26.         <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  27.  
  28.         <!-- Echo all executed SQL to stdout -->
  29.         <property name="show_sql">true</property>
  30.  
  31.         <!-- Format the generated Sql -->
  32.         <property name="format_sql">true</property>
  33.  
  34.         <!-- Dont Drop and re-create the database schema on startup,Just update
  35.             it -->
  36.         <property name="hbm2ddl.auto">update</property>
  37.  
  38.         <mapping class="com.kb.model.Employee" />
  39.  
  40.     </session-factory>
  41.  
  42. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- Database connection properties -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<property name="hibernate.c3p0.min_size">5</property>
		<property name="hibernate.c3p0.max_size">30</property>
		<property name="hibernate.c3p0.timeout">120</property>
		<property name="hibernate.c3p0.max_statements">50</property>
		<property name="hibernate.c3p0.idle_test_period">2000</property>

		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>

		<!-- Format the generated Sql -->
		<property name="format_sql">true</property>

		<!-- Dont Drop and re-create the database schema on startup,Just update 
			it -->
		<property name="hbm2ddl.auto">update</property>

		<mapping class="com.kb.model.Employee" />

	</session-factory>

</hibernate-configuration>


hibernate.c3p0.min_size – Minimum number of JDBC connections in the pool.
Hibernate default: 1

hibernate.c3p0.max_size – Maximum number of JDBC connections in the pool.
Hibernate default: 100

hibernate.c3p0.timeout – When an idle connection is removed from the pool (in second).
Hibernate default: 0, never expire.

hibernate.c3p0.max_statements – Number of prepared statements that will be cached.
Hibernate default: 0 , caching is disable.

hibernate.c3p0.idle_test_period – idle time in seconds before a connection is automatically validated.
Hibernate default: 0

Step 5

Create the Main class to persist the Employee record

  1. package com.kb.db;
  2.  
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.Transaction;
  7.  
  8. import com.kb.model.Employee;
  9. import com.kb.util.HibernateUtil;
  10.  
  11. public class Main {
  12.     public static void main(String[] args) {
  13.         Transaction tx = null;
  14.         try {
  15.             // Get session factory using Hibernate Util class
  16.             SessionFactory sf = HibernateUtil.getSessionFactory();
  17.  
  18.             // Get session from Sesson factory
  19.             Session session = sf.openSession();
  20.  
  21.             // Begin transaction
  22.             tx = session.beginTransaction();
  23.  
  24.             // Creating Employee record
  25.             Employee employee = new Employee();
  26.             employee.setName("John");
  27.             employee.setCity("Newyork");
  28.  
  29.             session.save(employee);
  30.              try {
  31.                     Thread.sleep(20000);
  32.                 } catch (InterruptedException e) {
  33.                     e.printStackTrace();
  34.                 }
  35.  
  36.             tx.commit();
  37.             session.close();
  38.             System.out.println("successfully persisted all the Employee records");
  39.         } catch (HibernateException e) {
  40.             e.printStackTrace();
  41.             tx.rollback();
  42.         }
  43.     }
  44. }
package com.kb.db;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class Main {
	public static void main(String[] args) {
		Transaction tx = null;
		try {
			// Get session factory using Hibernate Util class
			SessionFactory sf = HibernateUtil.getSessionFactory();

			// Get session from Sesson factory
			Session session = sf.openSession();

			// Begin transaction
			tx = session.beginTransaction();

			// Creating Employee record
			Employee employee = new Employee();
			employee.setName("John");
			employee.setCity("Newyork");

			session.save(employee);
			 try {
					Thread.sleep(20000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			tx.commit();
			session.close();
			System.out.println("successfully persisted all the Employee records");
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
}


We are persisting one Employee record in the above class.

Step 6

Check the output in DB

connection_pool_hibernate_output1

Step 7

Verify the connection pool in MYsql workbench

connection_pool_hibernate_output2

We can see that 5 connections are opened as we specified minimum connections in the Pool to be 5.

Download this project HibernateConnectionPool.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on