How sleep mode provides second-level caching with the latest data in the database

I read that using the second level cache of sleep mode, it can improve application performance due to fewer database hits to retrieve data / objects.

However, how hibernate ensures that the second level cache is updated with the data in the database.

For example:

Assume that the class below is an entity and is stored in the database.

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

Now, if we turned on the second level cache, I understand that if we open different sessions, then each session falls into the second level cache to get the value of the object.

Now, if the data in the database receives changes (for example, for a row with id = 1), say, by some independent process / manually changing the values, and we try to access this value, as hibernate detects that the cache has the last value (for id = 1).

In general, how hibernate ensures that data in a second-level cache matches db values.

Thank you for your help.

+5
source share
2 answers

Hibernate manages the cache itself, so when you update an entity through a sleep session, it will invalidate the cache entry associated with this object, so the cache is always fresh. p>

If another process (or even a second JVM running the same sleeping application) updates a database record, Hibernate on the first JVM is not aware of this fact and has an outdated object in its cache.

However, you can use any cache implementation (cache provider) that you want. There are many vendors of ready-made cache data that let you configure how long a given object will be stored in the cache. For example, you can configure the cache to block all objects after 30 seconds, etc.

If you are using the EhCache cache provider, you can provide this configuration:

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

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

however, there are many useful guides about this.

+8
source

This is not true.

If you change the data in the database without using sleep mode, it will not know about it, and your cache and database will not synchronize.

+4
source

All Articles