ChatGPT解决这个技术问题 Extra ChatGPT

What are the First and Second Level caches in (N)Hibernate?

Can anyone explain in simple words what First and Second Level caching in Hibernate/NHibernate are?


d
dhS

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Quoted from: http://javabeat.net/introduction-to-hibernate-caching/


+1 for mapping First Level Cache with Session Object and Second Level Cache with Session Factory Object. i don't even needed to continue reading.
1-th level cache. in most cases it is not needed, but there is no option to get rid of it. but you should think about it all the time..
@ses You will need 1st level cache in most cases. Otherwise you will have very BAD PERFORMANCE problem like N+1 query, or no eager pre-fetch cache, or query once every time you access an attribute.
Usually we use session for very short period of time [and very body recommends it] / short lived session: we even do not use that cache in that period. if the session is long lived then we de-attach data (when edit form for example) from session. It seems it is needed only for one scenario when we trying to use query-session-api while building some complex request-after-request for long lived session.
@DennisCheung: The link is dead. Kindly update with javabeat.net/introduction-to-hibernate-caching
S
Samuel Liew

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.


that's simple words right there, I don't know why they have such hard time explaining it
hehe... yeah I don't really know how I could have gotten much simpler :)
this actually is more clearer for me. first is per session where second is for multi session, simple for me to keep in mind.can't we vote up twice? :D
there is not sample why 1th level cache is needed. as for me in most cases it is not needed at all. but you should think about it and about the session all the time.
Its 11 years since this answer and unfortunately the link does not exist now. But I found its content on its archive webpage: web.archive.org/web/20081207044228/http://…
P
Piotrek Hryciuk

Here some basic explanation of hibernate cache...

First level cache is associated with “session” object. The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Second level cache is apart from first level cache which is available to be used globally in session factory scope. second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.


Excellent explanation ! If you could draw some sequence diagrams it will be awesome !!!
thorough and nice explanation
If you are looking to revise what you already know, then the above two answers by Dennis C and Iomaxx are great, very succinct, and easy to remember. If however, you are looking for an explanation of the difference when you don't already know it, this answer is much better!
Great explanation!!
V
Vlad Mihalcea

First-level cache

Hibernate tries to defer the Persistence Context flushing up until the last possible moment. This strategy has been traditionally known as transactional write-behind.

The write-behind is more related to Hibernate flushing rather than any logical or physical transaction. During a transaction, the flush may occur multiple times.

https://i.stack.imgur.com/UXmRs.png

The flushed changes are visible only for the current database transaction. Until the current transaction is committed, no change is visible by other concurrent transactions.

Due to the first-level cache, Hibernate can do several optimizations:

JDBC statement batching

prevent lost update anomalies

Second-level cache

A proper caching solution would have to span across multiple Hibernate Sessions and that’s the reason Hibernate supports an additional second-level cache as well.

The second-level cache is bound to the SessionFactory life-cycle, so it’s destroyed only when the SessionFactory is closed (typically when the application is shutting down). The second-level cache is primarily entity-based oriented, although it supports an optional query-caching solution as well.

When loading an entity, Hibernate will execute the following actions:

https://i.stack.imgur.com/GJkmR.png

If the entity is stored in the first-level cache, then the cached object reference is returned. This ensures application-level repeatable reads. If the entity is not stored in the first-level cache and the second-level cache is activated, then Hibernate checks if the entity has been cached in the second-level cache, and if it were, it returns it to the caller. Otherwise, if the entity is not stored in the first or second-level cache, it will be loaded from the DB.


D
Dori

by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.

so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.


M
MD RAHIIM

First Level Cache

Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.

Second Level Cache

SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.


P
Prakash Bayas

In a second level cache, domain hbm files can be of key mutable and value false. For example, In this domain class some of the duration in a day remains constant as the universal truth. So, it can be marked as immutable across application.