java Hibernate 查询缓存在外部更新时自动刷新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2783292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate query cache automatically refreshed on external update?
提问by artgon
I'm creating a service that has read-only access to the database. I have a query cache and a second level cache enabled (READ_ONLY mode) in Hibernate to speed up the service, as the tables being accessed change rarely.
我正在创建一个对数据库具有只读访问权限的服务。我在 Hibernate 中启用了查询缓存和二级缓存(READ_ONLY 模式)以加快服务速度,因为被访问的表很少更改。
My question is, if someone goes into the DB and changes the tables manually (i.e. outside of Hibernate), does the cache recognize automatically that it needs to be cleared? Is there a time limit on the cache?
我的问题是,如果有人进入数据库并手动更改表(即在 Hibernate 之外),缓存是否会自动识别需要清除它?缓存有时间限制吗?
采纳答案by Affe
Nope, the cache isn't going to scan the database for you to magically update itself when the underlying data changes. Changes that do not come through the L2 cache will not appear in it. How long it takes to time out etc. depends on your provider and whatever the default settings are. It looks like the default ehcache.xml is for 2 minutes.
不,缓存不会扫描数据库让您在底层数据更改时神奇地更新自己。未通过 L2 缓存的更改将不会出现在其中。超时等需要多长时间取决于您的提供商以及默认设置。看起来默认的 ehcache.xml 是 2 分钟。
回答by Pascal Thivent
If you don't go through Hibernate APIs to make your changes, the second-level-cache won't get notified and the changes won't be visible. The usual way to deal with this situation is to evict the corresponding objects from the second-level-cache programatically to force a refresh. The SessionFactoryprovides methods allowing to do this. From the section 19.3. Managing the cachesof the documentation:
如果您不通过 Hibernate API 进行更改,则二级缓存将不会收到通知并且更改将不可见。处理这种情况的常用方法是通过编程从二级缓存中驱逐相应的对象以强制刷新。该SessionFactory规定允许这样做的方法。来自第19.3节。管理文档的缓存:
For the second-level cache, there are methods defined on
SessionFactoryfor evicting the cached state of an instance, entire class, collection instance or entire collection role.sessionFactory.evict(Cat.class, catId); //evict a particular Cat sessionFactory.evict(Cat.class); //evict all Cats sessionFactory.evictCollection("Cat.kittens", catId); //evict a particular //collection of kittens sessionFactory.evictCollection("Cat.kittens"); //evict all kitten collections
对于二级缓存,定义了
SessionFactory用于驱逐实例、整个类、集合实例或整个集合角色的缓存状态的方法。sessionFactory.evict(Cat.class, catId); //evict a particular Cat sessionFactory.evict(Cat.class); //evict all Cats sessionFactory.evictCollection("Cat.kittens", catId); //evict a particular //collection of kittens sessionFactory.evictCollection("Cat.kittens"); //evict all kitten collections

