I have read that using hibernate's second level cache, it can improve applications performance by having less database hits for data / object retrieval.
However, how does hibernate ensure that second level cache is up to date with the data in database.
For, example:
Suppose the below class is entity and persisted into the DB.
@Entity
class User {
Id
private int id;
private String str;
}
Now, if we have enabled second level cache, I understand that if we open different sessions then each session will hit the second level cache for retrieving object value.
Now, if data in database gets changes (for e.g. for row with id=1) say by some independent process/ manually changing the values, and we try to access the value, how does hibernate detect that the cache is having latest value (for id = 1).
In general, how does hibernate ensure that data in second level cache is consistent with the db values.
Thanks for your help.
Hibernate manages the cache himself, so when you update some entity thru hibernate Session it will invalidate cache entry assocciated with this entity - so cache is always fresh.
If another process (or even second JVM running the same hibernate application) updates record in database, Hibernate on first JVM is unaware of this fact and has stale object in his cache.
However you can use any cache implementation (cache provider) you want. There are many production-ready cache providers that allow you to configure how long given entity will be stored in cache. For example you can configure your cache to invalide all entities after 30 seconds and so on.
If you use EhCache cache provider you can provide such configuration:
<cache name="com.my.company.Entity"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="7200"
timeToLiveSeconds="7200"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
You can find more information abount L2 cache here: http://www.tutorialspoint.com/hibernate/hibernate_caching.htm
however there is a lot of useful tutorials about this.