Hibernate c3po Connection pooling
0
**What is the connection pool? **
Connection pooling is a technique to open or prepare or close connections. A connection pooling mechanism, which is managing connections. If our application requires a connection, then connection pooling providing the connection, once task is completed the connection return back to the pool. The responsible of connection pooling opening N number of connections and leave them ready for when your application required. If a connection is invalid because out of idle time, the pooling mechanism will close it and reopen a new one. This represents a better usage of connections.
** Benefits of Connection pooling **
The connection pool is good for performance, as it prevents Java application create a connection each time when interacting with the database and minimizes the cost of opening and closing connections.
Hibernate supports a variety of connection pooling mechanisms. Below are the Hibernate supported connection pools.
- C3po.
- ADBCP(Apache DBCP).
- Proxool.
Here i am going to implement the connection pooling with c3po.
What is c3p0 ?
C3P0 is an open source connection pool which has a Hibernate package which you can add as a dependency to your project and you are ready to configure the pool.
Following is some sample code.
1) pom.xml
Below dependency isrequired to add in pom.xml
**2) Configure c3p0 propertise in hibernate.cfg.xml file **
- hibernate.c3p0.min_size – The minimum number of connections in the pool. Hibernate default no of connections: 1
- hibernate.c3p0.max_size – The maximum number of connections in the pool. Hibernate default no of connections: 100
- hibernate.c3p0.timeout –Idle connection is removed from the pool (in second). Hibernate default: 0, it means the connection never expires.
- hibernate.c3p0.max_statements – The number of prepared statements will be cached. Increase performance. Hibernate default: value is 0, it means caching is disabled.
- hibernate.c3p0.idle_test_period – idle time in seconds before a connection is automatically validated. Hibernate default value is: 0
- hibernate.c3p0.acquireRetryAttempts: Defines how many times c3p0 will try to acquire a new Connection from the database before giving up. If this value is less than or equal to 0, c3p0 will keep trying to fetch a Connection indefinitely.
- hibernate.c3p0.acquireRetryDelay: Milliseconds, time c3p0 will wait between acquiring attempts.
3) Employee.java
4) ConnectionPoolTest.java
** Note **
Hibernate comes with the internal connection pool, it is not suitable for production use, so we should implement hibernate supported connection pooling for production.