Hibernate Second Level Cache Example – Ehcache configuration example

Welcome to the Hibernate Second Level Cache Example tutorial. Now, we will taking a ehcache configuration example to clarify about Hibernate Second Level Cache. EHCache is the most popular Hibernate Second Level Cache provider.

One important thing, we should know different strategies for caching an object:

Read Only: It should be used for persistent objects that will be always read but never updated. The read-only strategy is the simplest and with best performance because no need to check if an object is updated in database or not.
Read Write: This strategy is suitable for the hibernate application whose data is updated. Just a exception, the data is updated in database through other applications and Hibernate is out of control in this case. So while using this strategy, we have to make sure our application and other applications are using Hibernate API for updating the data.
Nonrestricted Read Write: If the application rarely needs to update data and strict transaction isolation is not required, we may use the nonstrict–read–write strategy. It has less overhead than read-write.
Transactional: We can use this strategy if we need a fully transactional cache. However, it is only suitable in a JTA environment and we must specify hibernate.transaction.manager_lookup_class.

EHCache is the best choice when we are looking for second level cache in hibernate. EHCache supports all the above cache strategies. We will create examples to know how EHCache works for hibernate application.

Other interesting posts you may like

Create project directory structure

In this Hibernate Second Level Cache Example, we are creating a maven project in the Eclipse, final project directory structure will look like below image

Hibernate Second Level Cache Example, Ehcache configuration example

Maven Dependencies

We would provide ehcache-core and hibernate-ehcache dependencies in pom.xml file. Beside EHCache uses slf4j for logging, so we also add slf4j-simple dependencies in pom.xml file. Of course, don’t forget add hibernate-core and mysql-connector-java dependencies.

Our pom.xml like below:

Hibernate Configuration file

As you know Hibernate Second level cache is disabled by default, so we enable it and add some configurations like below:

Let’s dig deeper:

The hibernate.cache.region.factory_class property is used to define Factory class that we use for Second level cache. In this case, we are using org.hibernate.cache.ehcache.EhCacheRegionFactory. Or using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory class when we want the factory class to be singleton.
The hibernate.cache.use_second_level_cache property is used to enable the second level cache in hibernate application.
The hibernate.cache.use_query_cache property is used to enable the query cache, so that HQL queries results will be cached.
The net.sf.ehcache.configurationResourceName property is used to define location of EHCache configuration file. This property is an optional and if it’s not set EHCache will try to find it in the application classpath.

Hibernate EHCache Configuration File

Our EHCache configuration file looks like below.

Hibernate EHCache provides a lot of options, I won’t go into much detail but some of the important configurations above are:

diskStore: EHCache stores data into memory by default. However, it will start to writing data into file system on disk when the memory is overflowed. This property defines the location where EHCache can write on disk.

defaultCache: This is a mandatory configuration, if there is no caching region defined the defaultCache will be used.

cache name=”student”: we can define the cache region by using the cache property. We can define multiple cache regions with caching strategies.

Cache regions org.hibernate.cache.internal.StandardQueryCache and org.hibernate.cache.spi.UpdateTimestampsCache is used for Query Cache. The org.hibernate.cache.internal.StandardQueryCache region will holds the cached query results. The org.hibernate.cache.spi.UpdateTimestampsCache region will holds timestamps of the most recent updates to queryable tables. These timestamps validate results served from the query cache.

You can refer to the ehcache.xml via this link

Model Bean Caching Strategy

We create a Model bean like below:

Let’s dig deeper:

@Cache annotation to enable the caching configuration.
The attribute CacheConcurrencyStrategy is used to define the caching strategy
The attribute region is used to define the cache region for the model beans.

Create Hibernate Utility class

For configuring hibernate on startup and managing session factory we create the HibernateUtil class like this:

Create test program for

Our Hibernate Second Level Cache Example will demonstrate two cases using Hibernate EHCache:

Case 1: Load data with same session object.

Run above program and we get the output like below:

Step by step explanation of the output is as follows:

At the step 0: Our Second Level cache is empty, all the statistics are 0 as expected.
At the step 1: We loaded a student. Hibernate found this object in the Second Level cache firstly, if it doesn’t exist Hibernate looked up in database. It’s is reason why query log is fired. And this student object was stored in Hibernate Second Level Cache, the Second Level Put Count is set to 1.
At the step 2: There is no change with Statistics of Second Level cache. Because First Level cache is still enable and Hibernate looked up in it firstly. If object was found in the First Level cache Hibernate would skip over Second Level cache.
At the step 3: Firstly, we did evict student object in First Level cache. Then we loaded a student again. Hibernate first looked up in the First Level cache, but this object didn’t exist. Then Hibernate looked up in the Second Level cache so that Second Level Hit Count was set to 1.

Case 2: Load data with two other session objects.

Run above main and we get the output like below:

Step by step explanation of the output is as follows:

At the step 0: Our Second Level cache was empty, all the statistics was 0 as expected.
At the step 1: We loaded a student by using session1. Hibernate found this object in the Second Level cache firstly, if it doesn’t exist Hibernate looked up in database. It’s is reason why query log is fired. And this student object was stored in Hibernate Second Level Cache, the Second Level Put Count is set to 1.
At the step 2: We loaded a student by using session2. However, Hibernate found this student object in Second Level Cache and the Second Level Hit Count is set to 1. And that’s reason why query log was not fired. Notice that this student object was stored in session1 but not in session2

That’s all on the Hibernate Second Level Cache Example, I hope it will help you in configuring EHCache in your hibernate applications and getting better performance through hibernate second level cache. You can download the sample project from below link and use other stats data to learn more.

Download complete source code, please click link below

HibernateEHCacheExample.zip (75 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons