Hibernate connection pooling in java

Hibernate Dbcp Connection Pooling Configuration

This tutorial shows you how to configure Hibernate dbcp Connection Pooling. By default hibernate comes with a built-in connection pool. But this connection pool is by no means production ready. They even advice not to use it in production, as you can see in the logging.

HHH10001002: Using Hibernate built-in connection pool (not for production use!)

Maven Dependencies

We are using Apache Maven to manage our project dependencies. Add the following dependencies to your projects pom.xml file.

 mysql mysql-connector-java 6.0.4  org.hibernate hibernate-core 5.2.3.Final  org.apache.commons commons-dbcp2 2.1.1  ch.qos.logback logback-classic 1.1.7 

Hibernate dbcp Connection Pooling Configuration

The database connections and hibernate dbcp connection pooling configuration are in the hibernate.cfg.xml file, located on the classpath in the src/main/resources folder.

By default, dbcp uses sensible defaults, but you can override these settings by setting the following properties.

     com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/bookstore?serverTimezone=Europe/Brussels root org.hibernate.dialect.MySQLDialect false create-drop 5 20 10 5 -1   
  • initialSize : The initial number of connections that are created when the pool is started.
  • maxTotal : The maximum number of active connections that can be allocated from this pool at the same time, or negative for no limit.
  • maxIdle : The maximum number of connections that can remain idle in the pool, without extra ones being released, or negative for no limit.
  • minIdle : The minimum number of connections that can remain idle in the pool, without extra ones being created, or zero to create none.
  • maxWaitMillis : The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely.

Demo

When using the previous configuration, dbcp initializes the connection pool with 5 connections at startup. So when we run the application – we can see in the following screenshot – that there are 5 connections waiting in the pool. Also that there is one active connection being used.

mariadb c3p0 hibernate connection pooling example

References

Источник

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:

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

   org.hibernate.dialect.MySQLDialect java:jboss/datasources/MySqlDS   

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:

 com.zaxxer HikariCP 5.0.1  org.hibernate hibernate-hikaricp $ 

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

org.hibernate.hikaricp.internal.HikariCPConnectionProvider 10000 20 300 200000

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:

 org.hibernate hibernate-c3p0 $ 

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:

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:

 org.hibernate hibernate-proxool 5.6.1.Final 

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

  mypool jdbc:mysql://localhost:3306/dbname com.mysql.jdbc.Driver 10 50  

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

    mypool proxool.xml // other configurations. 

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::

 mysql mysql-connector-java 6.0.5  org.apache.commons commons-dbcp2 2.1.1  

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; >

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

Recent Posts

WildFly books

wildfly books

Top 10 Tutorials

  • Configuring SSL/TLS with WildFly
  • Using WildFly on OpenShift
  • How to run CLI commands in WildFly Dockerfile
  • Monitoring Quarkus with Prometheus
  • Spring Boot on WildFly
  • Drools and Maven example project
  • Active MQ Performance Tuning
  • WildFly Interview Questions
  • DataSource pool configuration
  • Solving java.lang.OutOfMemoryError: Metaspace error
  • How to redirect HTTP to HTTPS in WildFly

Источник

Connection Pooling with Hibernate 4

We have arrived at a state with Hibernate 4 where we can change the database behind the system to go for production usage (so H2 databases are out of the question).

Now it is time to look at connection pooling, because the default connection pooling mechanism of Hibernate is rudimentary and is provided only for development and testing usage.

For the best performance and stability it is required to use a third-party tool. And there are some on the market and most of them are free and you can use them with ease along with Hibernate.

C3P0

Just like the golden translation and protocol robot of Star Wars, the mainly used connection pool provider is called c3p0.

C3P0 is an open source connection pool which has a Hibernate package which you can add as dependency to your project and you are ready to configure the pool:

 org.hibernate hibernate-c3p0 4.3.10.Final 

The most important configuration properties of the c3p0 connection pool are the following:

  • c3p0.min_size: Minimum number of JDBC connections in the pool. Hibernate default: 1
  • c3p0.max_size: Maximum number of JDBC connections in the pool. Hibernate default: 100
  • c3p0.timeout: When an idle connection is removed from the pool (in second). Hibernate default: 0, never expire.
  • c3p0.max_statements: Number of prepared statements will be cached. Increase performance. Hibernate default: 0 , caching is disable.
  • c3p0.idle_test_period – idle time in seconds before a connection is automatically validated. Hibernate default: 0

Configuration of C3P0

To configure C3P0 with your application you need the following properties set. In this case let’s see the already known XML-based configuration in hibernate.cfg.xml:

org.hibernate.c3p0.internal.C3P0ConnectionProvider 1 19 120 10

The first line with the connection provider is optional, you do not have to enter it, Hibernate will know that you are using C3P0. This is because the location (package structure) can change between Hibernate versions and it would be a pain in the neck to get an error every time you update to a newer version where the connection provider class is located at a different place.

If you look carefully in your log or console output when you start the server you should see that C3P0 is being configured:

org.hibernate.c3p0.internal.C3P0ConnectionProvider configure

Proxool

Proxool is an alternative connection pool to C3P0 however it requires more configuration so I personally favor C3P0.

It is not enough to have the dependency and your properties set, you need an extra XML file which contains the configuration information for Proxool.

The dependency is almost the same as for C3P0:

 org.hibernate hibernate-proxool 4.3.10.Final 

Configuration of Proxool

As I mentioned previously, it is not enough to configure Proxool in the hibernate.cfg.xml file, you need a separate XML file too:

org.hibernate.connection.ProxoolConnectionProvider proxool proxool.xml

As with C3P0 the first line, the hibernate.connection.provider_class is optional.

The XML file is mentioned in the hibernate.proxool.xml property.

The proxool.xml contains the following:

  proxool jdbc:h2:file:./example;DB_CLOSE_DELAY=-1;MVCC=TRUE org.h2.Driver 10 20  

As you can see, you have to provide the database connection in Proxool. This is mandatory. However because of this you can leave the connection configuration from the hibernate.cfg.xml file.

One drawback exists with Proxool: you have to define the dialect to use. With C3P0 and the default Hibernate configuration you don’t need to set the dialect to use but Proxool needs this information.

If everything is set-up you can see the following entry in your log or on the console when you start the application:

Generally about the configuration

Hibernate uses its magic to identify which connection pool provider to use — based on the properties you configure. However you can define the connection provider with the hibernate.connection.provider_class property.

If you do not configure a connection pool, the default is used. It is visible in the log or console output when you start the application:

org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure

Conclusion

There are some connection pool providers out there which you can easily bind together with Hibernate to give you a good database connection experience.

Configuring those providers is easy as most of them have their Hibernate integration package to import as a dependency to your project and get everything running.

Источник

Читайте также:  Style width property in html
Оцените статью