Hibernate: Story of Caching

Hi All,

In this blog, we are going to talk about caching in Hibernate.


Hibernate is an ORM Framework for Java. It is a framework for mapping Object-Oriented Model to Relational Model. Hibernate is concerned with data persistence as it applies to relational databases (via JDBC). It performs powerful object-relational mapping and query databases using HQL and SQL. It can cut down a lot of complexity and thus defects as well from your application, which may otherwise find a way to exist. We can also say it is a boon for developers with limited knowledge of SQL.


Caching is a mechanism to store data in a buffer memory (also known as cache) so that future request can be served faster. It helps in reducing the number of interaction to the database and enhance the performance of a system.

Why caching is important?

  • Enhance the performance of database applications.
  • Reduces traffic between your application and the database
  • Access database if data is not available in the cache.

Types of Cache:

First Level Cache
Second Level Cache
Query Cache

In this blog, we will focus on First level cache we will talk about Second Level & Query Cache in the next blog.

First Level Cache:

First level cache is Session cache. It is a session scoped cache which ensures that each entity instance is loaded only once in the persistent context. It is enabled by default & there is no way to disable it. As it is session-scoped cache all concurrent session work in isolation. Once the session is closed, its First Level cache is terminated as well.



Whenever an application tries to load an entity it searched in the First level cache if it is not able to find in first Level Cache it hits the database executes the query and store it in First level Cache and returns the result to the application.

Some Important methods to control first Level Cache:

First Level cache is default cache in Hibernate and there is no way to disable it. But Hibernate provides some method to control it.

evict(Object object):

It removes an object from session cache. After removing the object from the session, any change to object will not be persisted.


When this method called first level cache for that session is cleared. All the object from the cache.

contains(Object object):

This method can be used to check given instance is associated with this session.

In the next blog, we will look Second Level Cache.

Thanks for reading 🙂
Please like & share.