Difference between first level and second level cache in Hibernate

The main difference between first level and second level cache in Hibernate is that the first level is maintained at the Session level and accessible only to the Session, while the second level cache is maintained at the SessionFactory level and available to all Sessions. This means, you can use the first level cache to store local data i.e. the data which is needed by the Session and you can use the second level cache to store global data i.e. something which can be shared across sessions. This is also one of the frequently asked Hibernate Interview questions and popular in both telephonic rounds as well as on face to face interview, in both fresher and experienced level interviews.

That's why its important for a Java Hibernate Developer to understand how Caching works in Hibernate and what is the purpose of different caches provided by Hibernate. In this article, I'll explain about the First and Second level caches, how they work and what are key differences between them.

Caching is one of the powerful features of Hibernate and probably one of the strongest reason to use the Hibernate framework. It allows developers to build a more responsive web application by minimizing the number of database transactions.

Hibernate maintains different caches for the different purpose e.g. first level cache at Session level, Second level cache at the SessionFactory level and Query Cache to cache query and its results (see Introduction To Hibernate).

As the name suggests first level cache is the first cache hibernate consults before loading an object from the database. It is maintained at Session level and it's by default enabled.


If you know hibernate then you know that Session is the interface between Hibernate and Database. You load objects using Session e.g. by calling get() or load() method or by executing queries.

When you ask load method to return a Person (an object stored in database) with Id=1, first time it's loaded from database, that too lazily, when any method of that object is called other than getId(), next time if you load the same object then Hibernate doesn't go to Database, instead it returns the object from first level cache maintained at Session level.

Similarly when you update a particular object, Hibernate defer the database call to combine multiple database transactions into one, this way Hibernate improves the performance of your web application.

The data in the first level cache is maintained as long as Session is open, as soon as you close the Session all data is lost. next time even if you load the same object e.g. Person with the same id, Hibernate will again go to Database to load that object, provided Second-level Cache is disabled (see Java Persistence with Hibernate).

Difference between first level and second level cache in Hibernate


Btw, Caching at Session level has some memory implication, especially if you are loading lots of large objects. Long-lived sessions with several large objects will take more memory and can cause out of memory errors into your web application.

Now, let's come to second level cache. This is an optional Cache which Hibernate provides. Unlike first level cache which is accessible only to the session who maintains it, Second-level Cache is accessible to all Sessions.

This means if one Session loads an object e.g. Person with id=1 and Second session also loads the same object, only one database call will be made. Next session will get the data from Second-level Cache.

Difference between first level and second level cache in Hibernate


The Second Level cache is by default disabled. Hibernate also doesn't provide any caching implementation for that, instead, it provides CacheProvider interface and any third party Cache which implements CacheProvider interface can be hooked as Second level cache e.g. EHCache or NCache.

You also need to define Concurrency Strategy to be used along with Second level cache e.g. Transactions, read-write, nonstrict-read-write or read-only.

If you are interested in implementation details, I suggest you check out Introduction To Hibernate, a free course from Pluralsight to learn about how to implement Seco the d level cache in Java web application.

The second level cache can improve the performance of your Java Web application even further, but this should only be used to make a good application better and should not be used to address performance problem faced by the application.

You can also read, High-Performance Java Persistence by Vlad Mihalcea to learn how to tackle performance issues in the persistence layer. Vlad is an authority in Hibernate world and he has shared a lot of his practical advice in that book.



First level Cache vs Second-level Cache in Hibernate

Now that we have got some basic understanding of the first level and second level cache, here are some differences between them:

1) The first difference is that first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level.

2)  The data stored in the first level cache is accessible to the only Session who maintains it, while the Second level cache is accessible to all.

3) First level cache is by default enabled while the second level cache is by default disabled.

A couple of things to know about hibernate first level cache:

1) You can use Session.evict() to remove the loaded entity from the first level cache, can use refresh() method to refresh the cache and can use clear() method to remove all entities in cache.

2) You cannot disable the first level cache, it always enabled.

3) Hibernate entities or database rows remain in cache only until Session is open, once Session is closed, all associated cached data is lost.


That's all about the difference between 1st and 2nd level cache in Hibernate. Just remember that first level cache is local to Session object and cannot be shared between multiple sessions, but the second level cache is maintained at the SessionFactory level and shared among all sessions in Hibernate.


Further Learning
Spring and Hibernate for Beginners
2 Books to Learn Hibernate for Java developers
Difference between Save, SaveOrUpdate and Persist in Hibernate
Difference between transient, detached, and persistent objects
Top 5 Spring and Hibernate online training courses for Java developers
Why JPA or Hibernate Entity class should not be final?

Thanks for reading this article. If you like this Hibernate interview question and my explanation then please share with your friends and colleagues. If you have any feedback or questions then please drop a note. 

No comments:

Post a Comment