javaspring-boothibernatehibernate-cache

Hibernate cache levels 1 and 2


What is the difference between 1st level and 2nd level caching in Hibernate ?

Hi, I am learning Hibernate. I read some docs about 1st and 2nd level caching. What is the difference between them ? Its very hard to understand from the docs. It seems that they do the same thing and store some values in the JVM before pushing them to the database ... what is the difference actually ?


Solution

  • OK, so here's how you can look at it ...

    One of the most fundamental classes in Hibernate is the Session class.

    A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database

    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.

    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.

    This, in essence, explains the fundamental difference. 1st level cache -> mandatory and for only one session. 2nd level cache -> optional and shared by all sessions

    OK, so how can we use this functionality to make our life better and easier ?

    What are the uses cases for this ?

    You can find the details in this amazing post.