Clear Hibernate 2nd level cache after manually DB update

走远了吗. 提交于 2019-12-06 04:25:49

问题


Shortly, I have an entity mapped to view in DB (Oracle) with enabled 2nd level Cache (read only strategy) -- ehcache.

If I manually update some column in DB -- cache will not be updated.

I did not find any ways to do this. Only if updates will be done through Hibernate entity.

May I somehow implement this feature?

Maybe Job to monitor table (or view)? Or maybe there is some method to notify Hibernate about change in DB in concrete table.

Thanks for future answers!


回答1:


According to Hibernate JavaDoc, you can use org.hibernate.Cache.evictAllRegions() :

evictAllRegions() Evict all data from the cache.

Using Session and 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.
}

1) If you need update only one entity (if directly from db you will update only certain entities) not whole session, you can use

evictEntityRegion(Class entityClass) Evicts all entity data from the given region (i.e.

2) If you have a lot of entities, that can be updated directly from db you can use this method that evicts all entities from 2nd level cache (we can expose this method to admins through JMX or other admin tools):

/**
 * 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);
    }
}

3) Another approach is described here for postgresql+hibernate, I think you can do something similar for Oracle like this




回答2:


You can use session.refresh() method to reload the objects which are currently held in session.

Read object loading for more detail.




回答3:


You will find here the way to control the second level cache:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-sessioncache




回答4:


As of JEE 7.0:

myStatelessDaoBean.getSession().evict(MyEntity.class);


来源:https://stackoverflow.com/questions/40302097/clear-hibernate-2nd-level-cache-after-manually-db-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!