Hibernate 5 - c3p0 connection pool configuration example




Technologies used:   Java SE 1.8 | Hibernate 5.2.10.Final | c3p0 0.9.5.2 | Maven 3.3.9 | MySQL 5.7.12 | Eclipse Neon.3

C3p0 is an open source JDBC connection pooling library, with support for caching and reuse of PreparedStatements.

Hibernate provides support for java application to use c3p0 for connection pooling with additional configuration settings.

In this section, I will show you how to configure c3p0 library with Hibernate ORM framework.

 

Jar Dependencies

In pom.xml file of your maven project, add  hibernate-corehibernate-c3p0, c3p0 and mysql-connector-java dependencies as follows.

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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.boraji.tutorial.hibernate</groupId>
  <artifactId>hibernate-c3p0-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hibernate-c3p0-example</name>
  <url>http://maven.apache.org</url>

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

  <dependencies>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>

    <!-- Hibernate ORM -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

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

    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

 

Hibernate + C3p0 configuration

To enable c3p0 connection pooling, add the following c3p0 configuration settings in HibernateUtil class.

// c3p0 configuration
settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted 
settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time
settings.put(Environment.C3P0_MAX_STATEMENTS, 150); //PreparedStatement cache size

You can pass the additional c3p0 parameters as follows-

settings.put(Environment.C3P0_CONFIG_PREFIX+".initialPoolSize", 5); 
// i.e. 'hibernate.c3p0.initialPoolSize'

For all available options in c3p0, refer this link - Configuration Properties

Here the complete HibernateUtil class to bootstrap hibernate application.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;

import com.boraji.tutorial.hibernate.entity.Person;

/**
 * @author imssbora
 */
public class HibernateUtil {

   private static StandardServiceRegistry registry;
   private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
      if (sessionFactory == null) {
         try {
            StandardServiceRegistryBuilder registryBuilder =
                  new StandardServiceRegistryBuilder();

            Map<String, Object> settings = new HashMap<>();
            settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
            settings.put(Environment.URL, "jdbc:mysql://localhost:3306/BORAJI?useSSL=false");
            settings.put(Environment.USER, "root");
            settings.put(Environment.PASS, "admin");
            settings.put(Environment.HBM2DDL_AUTO, "update");
            settings.put(Environment.SHOW_SQL, true);

            // c3p0 configuration
            settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
            settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
            settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted 
            settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time
            settings.put(Environment.C3P0_MAX_STATEMENTS, 150); //PreparedStatement cache size

            settings.put(Environment.C3P0_CONFIG_PREFIX+".initialPoolSize", 5);
            
            registryBuilder.applySettings(settings);
            
            registry = registryBuilder.build();
            MetadataSources sources = new MetadataSources(registry)
                  .addAnnotatedClass(Person.class);
            Metadata metadata = sources.getMetadataBuilder().build();
            sessionFactory = metadata.getSessionFactoryBuilder().build();
         } catch (Exception e) {
            if (registry != null) {
               StandardServiceRegistryBuilder.destroy(registry);
            }
            e.printStackTrace();
         }
      }
      return sessionFactory;
   }

   public static void shutdown() {
      if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
      }
   }
}

 

Entity class

A simple model class with JPA annotations.

Person.java

package com.boraji.tutorial.hibernate.entity;

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

@Entity
@Table(name = "PERSONS")
public class Person {
  @Id
  @GeneratedValue
  @Column(name = "ID")
  private Long id;

  @Column(name = "NAME")
  private String name;

  //Getter and Setter
}

 

Run Application

Create the MainApp class to test the c3p0 and Hibernate configuration.

MainApp.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Person;

/**
 * @author imssbora
 */
public class MainApp {

   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         Person person = new Person();
         person.setName("Mike Lewis");
         session.save(person);

         transaction.commit();
      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }
}

On execution the MainApp class, the console output will look like as follows.

Hibernate 5 + c3p0 configuration example | BORAJI.COM

 

 

Download Source: