手动更新数据库后清除 Hibernate 二级缓存

Art*_*aka 9 java oracle caching hibernate ehcache

很快,我有一个实体映射到 DB (Oracle) 中的视图,并启用了第二级缓存(只读策略)——ehcache。

如果我手动更新数据库中的某些列 - 缓存将不会更新。

我没有找到任何方法来做到这一点。仅当更新将通过 Hibernate 实体完成时。

我可以以某种方式实现这个功能吗?

也许工作来监视表(或视图)?或者也许有一些方法可以通知 Hibernate 关于具体表中 DB 的变化。

感谢未来的答案!

Dan*_*yar 5

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

evictAllRegions() 从缓存中驱逐所有数据。

使用 Session 和 SessionFactory:

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)

1)如果你只需要更新一个实体(如果直接从数据库你只会更新某些实体)而不是整个会话,你可以使用

evictEntityRegion(Class entityClass) 从给定区域驱逐所有实体数据(即

2) 如果您有很多实体,可以直接从 db 更新,您可以使用此方法从二级缓存中驱逐所有实体(我们可以通过 JMX 或其他管理工具将此方法公开给管理员):

/**
 * Evicts all second level cache hibernate entites. This is generally only
 * needed when an external application modifies the game databaase.
 */
public void evict2ndLevelCache() {
    try {
        Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
        Cache cache = sessionFactory.getCache();
        for (String entityName : classesMetadata.keySet()) {
            logger.info("Evicting Entity from 2nd level cache: " + entityName);
            cache.evictEntityRegion(entityName);
        }
    } catch (Exception e) {
        logger.logp(Level.SEVERE, "SessionController", "evict2ndLevelCache", "Error evicting 2nd level hibernate cache entities: ", e);
    }
}
Run Code Online (Sandbox Code Playgroud)

3)这里为 postgresql+hibernate描述另一种方法,我认为你可以像这样为 Oracle 做类似的事情