Second level EHCache example in Hibernate

This tutorial will sow how we can configure second level cache using ehcache in Hibernate step by step. EH stands for Easy Hibernate. We know that tehre are three types of caching mechanism such as First Level – session, Second Level – SessionFactory and Query Level – SessionFactory.

For more information on First Level, Second Level and Query Level please go through Hibernate Caching strategy.


MySQL Database 5.5
JDK 1.6
MySQL Connector jar
Hibernate jars
Hibernate SessionFactory Second Level EHCache example

Create a MySQL table called cd


Insert some data


Create POJO and hibernate mapping file for the database table


The above pojo file is simple and easy to use. It just declares the attributes same as in the database table.

mapping file – CD.hbm.xml


The mapping file is simple and easy to understand. In the above mapping file I have used


use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.

Now we need to configure hibernate to connect the database table as well as to use the second level cache for ehcache. Below is the hibernate.cfg.xml file


I will explain each of the property tag here

Below property denotes what type of Dialect should be used for the database.

Below property denotes which driver class should be used based on the database

Below is the full database URL with host, port and database instance. zeroDateTimeBehavior=convertToNull will convert ‘0000-00-00 00:00:00’ or ‘0000-00-00’ to null value.


Below denotes username of the database.


Below denotes password for the database. I don’t have password for my database so I didn’t use this property.


Which session context we should use. Possible values are jta, thread and managed. I use thread.


Below is the query parser for performing the translation


Show generated sql in the console


Format the generate sql query in the console for better readability


Hibernate gives some useful metrics like Entity Insert/Delete/Load/Fetch count, Query Cache hit/miss/put/get count etc.


Force Hibernate to keep the cache entries in a more readable format.


Use below property to use the second level cache in Hibernate.


Below property denotes that we are using second level cache for EhCache


This is the mapping xml file to the java object with the database table


Below property indicates if the ehcache.xml file located in other than classpath location. If you place your ehcache.xml file in the classpath then you don’t need to put this property in the hibernate configuration.


Nest step is to configure the ehcache.xml file and put it under classpath, i.e., in the src folder.

ehcache.xml looks like below


In this file there are few things to mention –

diskStore: EhCache stores data into memory but when it starts overflowing, it start writing data into file system. We use “path” property to define the location where EhCache will write the overflown data.

defaultCache: It’s a mandatory configuration, it is used when an object need to be cached and there are no caching regions defined for that.

cache name=”in.webtuts.domain.CD”: We use cache element to define the region and its configurations. We can define multiple regions and their properties. While we define model beans cache properties, we can also define region with caching strategies.

In ehcache.xml if eternal=”true” then we should not write timeToIdealSeconds, timeToLiveSeconds because Hibernate will take automatically care about those values. So if you want to give values for timeToIdealSeconds, timeToLiveSeconds then use better eternal=”false” always.

In ehcache.xml timeToIdealSeconds=”seconds” means, if the object in the global chche is idle for sometime, means not using by any other class or object then it will be waited for the time we have specified in timeToIdealSeconds and it will be deleted from the global cache if time is exceeds more than timeToIdealSeconds value.

In ehcache.xml timeToLiveSeconds=”seconds” means the other Session or class using this object or not, whatever the situation occurrs, when the time exceeds timeToLiveSeconds value then it will be removed from the global cache by hibernate.

Now we will create file which will give us the Singleton SessionFactory.


The above class is simple and easy to understand.

Next we write the for testing our work.


Note that for a cached query, the cache miss is equals to the db count

Once you run the then you will see the following output


I will explain here about the output.

1. First we get the below statistics and all are 0 because we don’t have any Session, Transaction etc.


2. Then we save one CD entity because we have to test with this entity. We open the “dbSession1” and start the transaction “dbTransaction1”. Then we load “cd1” entity from the database as the database has been hit for loading the data.


Then “cd2” entity is loaded from the first level session because in this case database was not hit and session was also not closed while fetching the data as it is clear from the below output.


So here we get the below statistics


All have obvious meaning. Note that the cache miss is equal to the db count. Put count is the count of storing the data in cache.

Whenever the data is stored in first level then the data is also stored in the second level cache.

Note we need to close the Session after each transaction for getting the obvious output.

3. If you look at ehcahe.xml we have timeToIdleSeconds=”3″ so, it means after 3 idle seconds the session gets expired.
Now if you look carefully at file then you will find Thread.sleep(5000) so we are here waiting for 5 seconds and it is obvious that the second level cache must expire by this time. So we get the below output after “Waiting….” for “cd3” entity.


So the above output is obvious and “db count”, “miss count”, “put count” have been increased by 1.

4. Now we load the “cd4” entity and get the below output


In the above output db count, miss count and put count are same but fetch count has been increased by 1 because we have got this entity from the second level cache.

How do we know that it is coming from second level cache ?

We had opened new session and started new transaction for fetching this “cd4” entity.

Thanks for your reading. Please do not forget to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.