Difference between first level and second level cache in Hibernate

The main difference between the 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 accessible in both telephonic rounds as well as on the face-to-face interviews, in both fresher and experienced level interviews.

That's why it's 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 the First and Second level caches, how they work, and are fundamental differences between them.

Caching is one of the powerful features of Hibernate and probably one of the most substantial reasons 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 different purposes, like the first level cache at Session level, Second level cache at the SessionFactory level, and Query Cache to cache query and its results (see Spring and Hibernate for Beginners course on Udemy).




What is First Leven Cache in Hibernate?

As the name suggests, the first-level cache is the first cache hibernate consults before loading an object from the database. It is maintained at the 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, like by calling get() or load() method or by executing queries.

When you ask the load method to return a Person (an object stored in the database) with Id=1, the first time it's loaded from the 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 a 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, like a Person with the same id, Hibernate will again go to Database to load that object, provided Second-level Cache is disabled (). 

By the way, Caching at the Session level has some memory implications, 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 in your web application. You can further see Master Hibernate and JPA with Spring Boot in 100 Steps course on Udemy to learn more about Hibernate advantages. 

Hibernate Cache Architecture




What is Second-Level Cache in Hibernate?

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

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

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

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

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

Difference between first level and second level cache in Hibernate



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

You can also read, High-Performance Java Persistence course by Vlad Mihalcea, one of the best resources to learn how to implement a real-world, high-performance persistence layer using Hibernate and JPA. 

Vlad is an authority in the Hibernate world, a Java Champion, and also a contributor to the Hibernate project. He has shared a lot of practical advice in this course and I highly recommend this to every Hibernate developer.

first level vs second level cache in Hibernate




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 primary difference is that the first level cache is maintained at the Session level while the second level cache is maintained at the SessionFactory level.

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

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

A couple of things to know about Hibernate's first level cache:

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

2) You cannot disable the first level cache, it is 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 the first-level cache is local to the 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. 

Caching is the best thing Hibernate offer, without too much from Developer's side, hence I recommend you to learn more about Caching and how to effectively use in your project. If you want to go deeper, the following resources are great for further learning.


Other Hibernate Articles and Interview Questions you may like
  • Top 5 Courses to learn Hibernate and JPA in-depth (courses)
  • Difference between First and Second level cache in Hibernate? (answer)
  • Difference between get() and load() method in Hibernate? (answer)
  • 5 Spring and Hibernate Training Courses for Java developers (list)
  • 2 Books to Learn Hibernate for Beginners (books)
  • 5 Online Courses to learn Spring Boot for Beginners (courses)
  • 5 Books to Learn Spring Framework for Java developers(books)
  • Why Hibernate Entity class should not be final in Java? (answer)
  • 10 Hibernate Questions from Java Interviews (list)
  • Top 15 Spring Boot Interview Questions for Java Programmers (questions)
  • Top 5 Courses to learn Spring Framework in-depth (courses)
  • 5 Essential Java Frameworks for Developers (frameworks)
  • 10 Free Spring Boot Courses for Java Programmers (free courses)

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

8 comments:

  1. But how second level cache works?...How many hits to database? While accessing data from cache and same time do updated what happens in this case

    ReplyDelete
  2. Excellent Explanation! Thank you!!!

    ReplyDelete
  3. Excellent Explanation! Thank you!!!

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.