December 13, 2013 | Posted in:tools

Detailed steps to configure simple in-memory cache using C3P0 and ehCache in Hibernate ORM library

We need to configure in memory caching in hibernate using C3P0 and ehCache so often that we thought writing a simple post about it would help our new team members and java developers out there alike. So here are the detailed steps to configure caching in hibernate with C3P0 and ehCache below.

Following are the configurations for c3p0 connection pool:

These go in your hibernate.cfg.xml file,
 <property name=”connection.provider_class”>org.hibernate.connection.C3P0ConnectionProvider</property>
<property name=”hibernate.connection.autoReconnect”>true</property>
<property name=”hibernate.c3p0.acquire_increment”>3</property>
<property name=”hibernate.c3p0.idle_test_period”>5</property>
<property name=”hibernate.c3p0.max_size”>50</property>
<property name=”hibernate.c3p0.max_statements”>0</property>
<property name=”hibernate.c3p0.min_size”>0</property>
<property name=”hibernate.c3p0.timeout”>5</property>
<property name=”hibernate.c3p0.idleConnectionTestPeriod”>5</property>

initialPoolSize C3P0 default: 3

 minPoolSize default: 1

maxPoolSize default: 100 , no of connections that the applications will to serve at once.

idleTestPeriod default: 0 , If this is a number greater than 0, c3p0 will check for all idle pooled connections every this number of seconds.

timeout default is 0 The seconds a Connection can remain pooled but unused before getting closed. 0 means connections never expire.

maxStatements default: 0 The size of Prepared Statement cache. Zero means statement caching is off.

acquireIncrement default: 1 no of connections c3p0 will try to acquire when the pool is exhausted.

You also can set extra c3p0 properties using c3p0.properties.

 

Following property should be added to configure ehcache:
 
This goes in your hibernate.cfg.xml file - 
<property name=”hibernate.cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>
What we have described here are simple configurations to get started with hibernate cache configurations. There are innumerable options and possibilities to fine tune hibernate cache for best performance and its dependent on your entity design. If you need assistance to do it right you can reach us for a free 30 minute consultation with one of our experienced technology / development team members. Contact Us here. 
email