Hibernate 2nd level cache invalidation when another process modifies the database

前端 未结 6 1129
[愿得一人]
[愿得一人] 2020-12-07 19:16

We have an application that uses Hibernate\'s 2nd level caching to avoid database hits.

I was wondering if there is some easy way to invalidate the Java application

6条回答
  •  眼角桃花
    2020-12-07 19:56

    Based on ChssPly76's comments here's a 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 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);
        }
    }
    

提交回复
热议问题