25

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

4

7 回答 7

34

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)的二级缓存驱逐。

于 2013-12-23T15:39:43.823 回答
17

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

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

于 2010-03-17T09:33:53.180 回答
3

如果您插入 Terracotta,您还可以运行 Terracotta 开发控制台,它可以检查有关缓存的统计信息、打开和关闭缓存以及从用户界面清除缓存内容。

JMX bean 也提供此功能。

于 2010-03-17T20:10:15.857 回答
2

@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.
    }
于 2019-08-30T20:04:28.670 回答
0

与@Dino 的回答相同,JPA 2.0 API 的缩短语法:

@Autowired
private EntityManagerFactory entityManagerFactory;

public void clearHibernateCaches() {
    entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}
于 2020-06-03T02:10:10.927 回答
0

如果要清除二级缓存,请使用 apisessionFactory.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);
    }
}

有关二级缓存的更多详细信息,请参阅

于 2015-10-26T06:56:20.133 回答
-10

你也可以用这个

request.getSession().invalidate();      
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
于 2015-01-29T07:43:49.087 回答