[英]Cache ignored using Spring 4 @Transactional + Hibernate 4 + EHCache
[英]How to clear all Hibernate cache (ehcache) using Spring?
我正在使用二級緩存和查詢緩存。 我可以知道如何以編程方式清除所有緩存嗎?
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.
}
或者,您可以清除特定范圍內的所有數據:
org.hibernate.Cache.evictCollectionRegions()
org.hibernate.Cache.evictDefaultQueryRegion()
org.hibernate.Cache.evictEntityRegions()
org.hibernate.Cache.evictQueryRegions()
org.hibernate.Cache.evictNaturalIdRegions()
您可能需要查看JavaDoc 以獲取 hibernate Cache interface (Hibernate 4.3) 。
此外,從休眠開發指南 (4.3) 中驅逐二級緩存。
要清除會話緩存使用session.clear()
要清除二級緩存,請使用此代碼片段
如果您插入 Terracotta,您還可以運行 Terracotta Dev Console,它可以檢查有關緩存的統計信息、打開和關閉緩存以及從用戶界面清除緩存內容。
JMX bean 也提供此功能。
@Dino 的回答幾乎對我有用,但我從sessionFactory.getCurrentSession()
得到一個錯誤(沒有配置 currentSessionContext!)。 我發現這對我有用:
// 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.