我正在使用第二级缓存和查询缓存。请问如何以编程方式清除所有缓存?
根据Hibernate JavaDoc,Bozho答案中指示的代码片段已经在Hibernate 4中被弃用。
您可以使用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.
}
或者,您可以清除特定范围的所有数据:
org.hibernate.Cache.evictCollectionRegions()
org.hibernate.Cache.evictDefaultQueryRegion()
org.hibernate.Cache.evictEntityRegions()
org.hibernate.Cache.evictQueryRegions()
org.hibernate.Cache.evictNaturalIdRegions()
您可能希望查看 Hibernate缓存接口的JavaDoc(Hibernate 4.3)。
此外,还可以查看 Hibernate开发指南(4.3) 中关于二级缓存淘汰的介绍。
@Dino的回答对我来说几乎有效,但是我从sessionFactory.getCurrentSession()
得到了一个错误(未配置当前会话上下文!)。 我发现这对我有用:
sessionFactory.openSession()
最初的回答。
// Use @Autowired EntityManager em
em.getEntityManagerFactory().getCache().evictAll();
// All of the following require org.hibernate imports
Session session = em.unwrap(Session.class);
if (session != null) {
session.clear(); // internal cache clear
}
SessionFactory sessionFactory = em.getEntityManagerFactory().unwrap(SessionFactory.class);
Cache cache = sessionFactory.getCache();
if (cache != null) {
cache.evictAllRegions(); // Evict data from all query regions.
}
与 @Dino 的答案相同,JPA 2.0 API 的简化语法:
@Autowired
private EntityManagerFactory entityManagerFactory;
public void clearHibernateCaches() {
entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}
如果您想清除二级缓存,请使用API sessionFactory.evictEntity(entityName)
代码:
/**
* Evicts all second level cache hibernate entites. This is generally only
* needed when an external application modifies the database.
*/
public void evict2ndLevelCache() {
try {
Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
for (String entityName : classesMetadata.keySet()) {
logger.info("Evicting Entity from 2nd level cache: " + entityName);
sessionFactory.evictEntity(entityName);
}
} catch (Exception e) {
logger.logp(Level.SEVERE, "SessionController", "evict2ndLevelCache", "Error evicting 2nd level hibernate cache entities: ", e);
}
}
关于二级缓存的更多细节请参阅
你也可以选择这个
request.getSession().invalidate();
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);