Hibernate Second Level Cache

Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory.

SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.

Different vendors have provided the implementation of Second Level Cache.

  1. EH Cache
  2. OS Cache
  3. Swarm Cache
  4. JBoss Cache

Each implementation provides different cache usage functionality. There are four ways to use second level cache.

  1. read-only: caching will work for read only operation.
  2. nonstrict-read-write: caching will work for read and write but one at a time.
  3. read-write: caching will work for read and write, can be used simultaneously.
  4. transactional: caching will work for transaction.

The cache-usage property can be applied to class or collection level in hbm.xml file. The example to define cache usage is given below:

Let's see the second level cache implementation and cache usage.

Implementationread-onlynonstrict-read-writeread-writetransactional
EH CacheYesYesYesNo
OS CacheYesYesYesNo
Swarm CacheYesYesNoNo
JBoss CacheNoNoNoYes

Hibernate Second Level Cache Example

To understand the second level cache through example, we need to follow the following steps:

  1. Create the persistent class using Maven
  2. Add project information and configuration in pom.xml file
  3. Create the Configuration file
  4. Create the class that retrieves the persistent object.

Here, we are assuming, there is emp1012 table in the oracle database containing some records.

1) Create the persistent class using Maven.

File: Employee.java

2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between <dependencies>....</dependencies> tag.


3) Create the Configuration file

File: hibernate.cfg.xml

To implement second level cache, we need to define cache.provider_class property in the configuration file.


4) Create the class that retrieves the persistent object.

File: FetchTest.java

Output:

hibernate second level cache output

As we can see here, hibernate does not fire query twice. If you don't use second level cache, hibernate will fire query twice because both query uses different session objects.






Latest Courses