How hibernate ensures second level cache is updated with latest data in database

本秂侑毒 提交于 2019-12-10 02:20:49

问题


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.


回答1:


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.




回答2:


It doesn't.

If you change data in the database without using hibernate it won't know about it and your cache and the database get out of sync.



来源:https://stackoverflow.com/questions/30413321/how-hibernate-ensures-second-level-cache-is-updated-with-latest-data-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!