Hibernate 二级缓存:无法驱逐

Hibernate 2nd level cache: Not able to evict

我正在使用 Hibernate 4.1.7 和 EhCache 作为二级缓存。我正在实施休息服务以根据需要清除 cahce(驱逐所有区域)。

下面是代码片段

org.hibernate.stat.Statistics statistics = HibernateUtil.getSessionFactory().getStatistics();
      statistics.setStatisticsEnabled(true);

      long hits = statistics.getSecondLevelCacheHitCount();
      long misses = statistics.getSecondLevelCacheMissCount();
      long puts = statistics.getSecondLevelCachePutCount();

      logger.info("Hits: " + hits + " Misses: " + misses +  " Puts:" + puts);


      cache.evictEntityRegions();

      hits = statistics.getSecondLevelCacheHitCount();
      misses = statistics.getSecondLevelCacheMissCount();
      puts = statistics.getSecondLevelCachePutCount();


      logger.info("Hits: " + hits + " Misses: " + misses +  " Puts:" + puts);         

      long hit0 = statistics.getQueryCacheHitCount();
      long miss0 = statistics.getSecondLevelCacheMissCount();

不幸的是,我得到 相同的 值 hits/misses 并在我驱逐所有区域之后放置。

这些计数具有以下含义:

  • 命中次数 - Hibernate 检查缓存中的对象并找到该对象(即已在缓存中)的次数
  • 未命中 - Hibernate 检查对象缓存但​​未在缓存中找到该对象的次数(因此需要从数据库中获取)
  • Puts - Hibernate 将对象放入缓存的次数

这些统计数据不会为您提供缓存中的当前项目数。考虑到这一点,清除缓存不会影响这些数字。

如果您想要重置统计信息,请使用

statistics.clear()

但是如果你想检查缓存的实际大小,你可以使用

CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("com.example.MyEntity").getSize();

请注意,每个实体都有自己的缓存,使用实体的完全限定 class 名称命名。