Java – how does hibernate ensure that the L2 cache is updated with the latest data in the database

I've read about using hibernate's L2 cache, which can improve application performance by reducing database hit data / objects

However, how does hibernate ensure that the L2 cache is synchronized with the data in the database

For example:

Suppose the following class is an entity and is persisted in dB

@Entity
class User {
    Id
    private int id;
    private String str;
}

Now, if we enable L2 caching, I understand that if we open different sessions, each session will access L2 cache to retrieve object values

Now, if the data in the database has changed (for example, for the row with id = 1) and a separate process / manually changes the value, we try to access the value. How does hibernate detect whether the cache has the latest value (for the row with id = 1)

In general, how does hibernate ensure that the data in the L2 cache is consistent with the DB value

Thanks for your help.

Solution

Hibernate manages the cache itself, so when you update an entity through a sleep session, it invalidates the cache entries associated with the entity - so the cache is always fresh

If another process (or even the second JVM running the same hibernate application) updates the records in the database, hibernate on the first JVM will not be aware of this fact and has obsolete objects in its cache

However, you can use any cache implementation (CACHE provider) you need There are many production ready cache providers that allow you to configure how long a given entity is stored in the cache For example, you can configure the cache to invalidate all entities after 30 seconds, and so on

If you use the ehcache cache provider, you can provide the following configurations:

<cache name="com.my.company.Entity" 
   maxElementsInMemory="1000" 
   eternal="false" 
   timeToIdleSeconds="7200" 
   timeToLiveSeconds="7200" 
   overflowToDisk="false" 
   memoryStoreEvictionPolicy="LRU"/>

You can find more information about L2 caching here: http://www.tutorialspoint.com/hibernate/hibernate_caching.htm

But there are many useful tutorials

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>