Hibernate second level cache - print result

为君一笑 提交于 2019-12-07 08:14:16

问题


I defined a second level cache in my application using @Cache annotation

I am using findById query, as the following:

  long id = 4;    
        Company cmp = companyDAO.findById(id);

Where Company is the object that I get from the DB.

How can I check if the Company object came from the DB or from the cache?


回答1:


Try HitCount and/or MissCount API.

Something like this.....

int oldMissCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getMissCount();
int oldHitCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getHitCount();

 long id = 4;    
 Company cmp = companyDAO.findById(id);

 int newMissCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getMissCount();
 int newHitCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getHitCount();
 if(oldHitCount+1 == newHitCount && oldMissCount+1 == newMissCount) {
    logger.debug("came from DB");
   }  else if(oldHitCount+1 == newHitCount && oldMissCount == newMissCount) {
    logger.debug("came from cache");
}



回答2:


How can I check if the Company object came from the DB or from the cache?

Hibernate uses a specific category to Log all second-level cache activity. The relevant category is org.hibernate.cache, just enable debug for it in the configuration of your logging framework.

See Chapter 3.5 Logging.




回答3:


Turn on cache logging.



来源:https://stackoverflow.com/questions/3156133/hibernate-second-level-cache-print-result

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