Configure Hibernate Connection Pool

This article discusses how to configure a JDBC Connection Pool in Hibernate applications covering both Hibernate managed applications and Hibernate Native applications.

A JDBC connection pool is a set of connections to a database that are created and maintained by an application, rather than creating a new connection each time it needs to interact with the database. There are several advantages to using a JDBC connection pool:

  1. Improved performance: Creating a new connection to a database can be a time-consuming process. By maintaining a pool of connections, an application can quickly and easily retrieve a connection from the pool, rather than waiting for a new connection.

  2. Reduced resource usage: Creating and maintaining a large number of connections can consume significant system resources, such as memory and network bandwidth. Using a connection pool can limit the number of connections in use.

Now let’s see which are the options you can use to configure a Connection Pool with Hibernate applications.

Hibernate Default Pool Configuration

Out of the box, Hibernate ships with Connection provider that uses the DriverManager directly to open connections and provides a rudimentary connection pool. The following properties are available

  • hibernate.connection.initial_pool_size: Minimum number of connections for the built-in Hibernate connection pool.
  • hibernate.connection.pool_size: Maximum number of connections for the built-in Hibernate connection pool
  • hibernate.connection.pool_validation_interval: The number of seconds between two consecutive pool validations.

For example, to configure the Connection Pool maximum pool size, you can apply this property in your XML Configuration:

<property name="hibernate.connection.pool_size">10</property>

Overall, the default Connection pool is not production ready and you should use it only for testing purposes.

Managed Connection Pool

Firstly, if your Database Connections are not managed directly by Hibernate but from a middleware (f.e. WildFly or Tomcat), then you can Connect to the Datasource via JNDI.

For example, this is a sample hibernate.cfg.xml configuration file that you can use to Connect to a MySQL Datasource available under the  the JNDI as java:jboss/datasources/MySqlDS

<hibernate-configuration>
    <session-factory>
            <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="connection.datasource">java:jboss/datasources/MySqlDS</property>
    </session-factory>
</hibernate-configuration>

Configure Hikari Connection Pool

If you are configuring the Connection Pool natively in your Hibernate application, then Hikari Connection Pool is the best choice.

HikariCP is fast, simple, and production ready connection pool that you can include in your project with the following dependencies:

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>5.0.1</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-hikaricp</artifactId>
    <version>${hibernate-version}</version>
</dependency>

Then, you will configure the Hikari Pool properties in your hibernate.cfg.xml. For example:

<property name="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</property>
<!-- Maximum waiting time for a connection from the pool -->
<property name="hibernate.hikari.connectionTimeout">10000</property>

<!-- Minimum number of ideal connections in the pool -->
<property name="hibernate.hikari.minimumIdle">20</property>

<!-- Maximum number of actual connection in the pool -->
<property name="hibernate.hikari.maximumPoolSize">300</property>

<!-- Maximum time that a connection is allowed to sit ideal in the pool -->
<property name="hibernate.hikari.idleTimeout">200000</property>

When you start your Hibernate Session you will see that

hibernate connection pool configuration

Finally, consider that if your Hibernate Application is running inside a Spring Boot runtime, the Connection Pool properties will be in the “spring.datasource” namespace. See the following article to learn more about Configuring Hikari Connection Pool with Spring Boot.

Configure C3P0 Connection Pool

C3P0 is an open source JDBC connection pool that is distributed with Hibernate. To configure the C3P0 connection pool, you need to add the following dependency to your project:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>${hibernate-version}</version>
</dependency>

Since Hibernate 5, just adding the above dependency is enough to enable c3p0. You can further customize your pool by setting the hibernate.c3p0.* properties. Example:

<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">30</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.timeout">1800</property>

Configure Proxool Connection Pool

Proxool is another opensource connection pool which can be configured as well in Hibernate. You will need the following dependency in your project:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-proxool</artifactId>
    <version>5.6.1.Final</version>
</dependency>

Additionally, Proxool requires its own configuration file (proxool.xml) in the same directory as the hibernate.cfg.xml file with the following content:

<proxool-config>
    <proxool>
        <alias>mypool</alias>
         
        <driver-url>jdbc:mysql://localhost:3306/dbname</driver-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <driver-properties>
            <property name="user" value="username"></property>
            <property name="password" value="password"></property>
        </driver-properties>
         
        <minimum-connection-count>10</minimum-connection-count>
        <maximum-connection-count>50</maximum-connection-count>
         
    </proxool>
 </proxool-config>

Then, within the hibernate.cfg.xml file you should remove the connection properties and delegate them to the proxool alias:

<?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>
          
    <property name="hibernate.proxool.pool_alias">mypool</property>
    <property name="hibernate.proxool.xml">proxool.xml</property>
                    
        // other configurations...
     
  </session-factory>
</hibernate-configuration>

Configure Apache DBCP 2 Connection Pool

Apache Connection Pool can be downloaded from http://commons.apache.org/dbcp/

Hibernate does not support automatic configuration for Apache commons dbcp2.

In order to integrate the Commons DBCP2 pool with Hibernate, you will need to add the following dependencies in your project::

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

   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
   </dependency>

As an example, you can create an instance of org.apache.commons.dbcp2.BasicDataSource as follows:

public static DataSource getDataSource() {
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
  dataSource.setUsername("user");
  dataSource.setPassword("password");

  // Connection pooling properties
  dataSource.setInitialSize(0);
  dataSource.setMaxIdle(5);
  dataSource.setMaxTotal(5);
  dataSource.setMinIdle(0);

  return dataSource;
}

Conclusion

This article was a walk through the Connection Pool configuration options available for Hibernate applications.

You can find a sample Hibernate 6 application with a demo HikariCP available on github at: https://github.com/fmarchioni/mastertheboss/tree/master/hibernate/HibernateExample

Found the article helpful? if so please follow us on Socials