如何使用Spring清除所有Hibernate缓存(ehcache)?

com*_*tta 22 java orm hibernate ehcache

我正在使用二级缓存和查询缓存.我可以知道如何以编程方式清除所有缓存吗?

Din*_*ino 31

Bozho答案中指出的代码片段在Hibernate 4中已弃用.

根据Hibernate JavaDoc,您可以使用org.hibernate.Cache.evictAllRegions():

从所有查询区域中删除数据.

使用API​​:

Session session = sessionFactory.getCurrentSession();

if (session != null) {
    session.clear(); // internal cache clear
}

Cache cache = sessionFactory.getCache();

if (cache != null) {
    cache.evictAllRegions(); // Evict data from all query regions.
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以清除特定范围内的所有数据:

org.hibernate.Cache.evictCollectionRegions()
org.hibernate.Cache.evictDefaultQueryRegion()
org.hibernate.Cache.evictEntityRegions()
org.hibernate.Cache.evictQueryRegions()
org.hibernate.Cache.evictNaturalIdRegions()
Run Code Online (Sandbox Code Playgroud)

您可能想要检查JavaDoc for hibernate Cache接口(Hibernate 4.3).

而且,hibernate开发指南(4.3)中的二级缓存逐出.


Boz*_*zho 18

清除会话缓存使用 session.clear()

要清除二级缓存,请使用此代码段

  • 对于现代版本的Hibernate,最好遵循@dino的答案. (5认同)