Search code examples
javahibernateehcachesecond-level-cache

problem in determining whether second level cache is working in hibernate


I am trying to use ehcache in my project.. i have specified the following properties in hibernate config file -

config.setProperty("hibernate.cache.provider_class","org.hibernate.cache.EhCacheProvider"); config.setProperty("hibernate.cache.provider_configuration_file_resource_path","ehcache.xml"); config.setProperty("hibernate.cache.use_second_level_cache","true"); config.setProperty("hibernate.cache.use_query_cache","true");

Now i am still not sure whether the results are coming from DB or the cache..

I looked around and found - Hibernate second level cache - print result where the person is suggesting HitCount/Misscount API's

However when i tried using it the hitcount and miss count is always returned 0... here's my code

String rName = "org.hibernate.cache.UpdateTimestampsCache"; Statistics stat = HibernateHelper.getInstance().getFactory().getStatistics(); long oldMissCount = stat.getSecondLevelCacheStatistics(rName).getMissCount(); long oldHitCount = stat.getSecondLevelCacheStatistics(rName).getHitCount(); UserDAO user = new UserDAO(); user.read(new Long(1)); long newMissCount = stat.getSecondLevelCacheStatistics(rName).getMissCount(); long newHitCount = stat.getSecondLevelCacheStatistics(rName).getHitCount();

if(oldHitCount+1 == newHitCount && oldMissCount+1 == newMissCount) { System.out.println("came from DB"); } else if(oldHitCount+1 == newHitCount && oldMissCount == newMissCount) {
System.out.println("came from cache"); }

Please let me know if i am using it wrong.. and what should be the rName(region Name) in this case..

Is there any other way of determining whether the second level cache is working ??

Thanks


Solution

  • You need to enable statistics collection:

    config.setProperty("hibernate.generate_statistics", "true");