Caching in Hibernate


Hibernate being one of the most preferred and popular ORM frameworks today, provides a very crucial feature alongside, which is caching.

Hibernate is a persistence framework that makes use of a Hibernate cache to persist the data from the Java environment to the database. The Hibernate cache helps in reducing the number of calls made to the database. Entities (which are nothing but the table records) are stored in the Hibernate cache, which contain the updated values.

Types of caching

There are two types of caching provided by Hibernate –

  1. First level cache
  2. Second level cache

First level cache is enabled by default for the current session.

Second level cache is not enabled by default and is available at the sessionFactory level, so the cached data is globally available to all the sessions created using the same sessionFactory object in the application. The second level cache needs to be enabled explicitly, which we will see when we integrate ehCache as the second level cache in our application.

Hibernate cache

So once the sessionFactory is closed, all the session data gets cleared out.

There are different vendors that provide the implementation of the Hibernate second level cache. To list the most popular ones are –

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

How does the second level cache work?

  1. Whenever we load an entity in Hibernate, the cached copy of the entity is searched in the first level cache of the current session.
  2. If the entity is found in the first level cache, it is returned successfully.
  3. If the entity is not found in the first level cache, the entity is searched in the second level cache.
  4. If the entity is found in the second level cache, the entity is returned as a result of load method, while storing the entity into the first level cache as well, for a better performance in the subsequent calls.
  5. If not found in the second level cache too, the database query is executed, and the loaded entity is cached at both first and the second level.

The second level cache automatically gets invalidated and updated whenever an entity is updated/deleted via Hibernate. However, if the database is updated directly without involving Hibernate, the second level cache won’t get invalidated automatically until ‘timeToLiveSeconds‘ duration is reached.

Alternatively, we can invalidate the second level cache explicitly as –

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.