hibernateehcache-2

Hibernate 2nd level cache: Not able to evict


I am using Hibernate 4.1.7 and EhCache as second level cache. I am implementing a rest service to clear cahce (evict all regions ) as needed.

Below is code snippet

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();

Unfortunately, I get same values for hits/misses and puts after I evict all regions.


Solution

  • These counts have the following meaning:

    These statistics don't give you the current number of items in the cache. With that in mind, clearing the cache wouldn't affect those numbers.

    If you do want to reset the statistics, use

    statistics.clear()
    

    But if you want to check the actual size of the cache you can use

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

    Note that each entity has its own cache, which is named using the fully-qualified class name for the entity.