【问题标题】:Hibernate second level cache - print resultHibernate 二级缓存 - 打印结果
【发布时间】:2011-03-10 12:38:06
【问题描述】:

我使用@Cache 注解在我的应用程序中定义了二级缓存

我使用的是 findById 查询,如下:

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

Company 是我从数据库中获取的对象。

如何检查 Company 对象是来自数据库还是来自缓存?

【问题讨论】:

    标签: hibernate caching second-level-cache


    【解决方案1】:

    如何检查 Company 对象是来自数据库还是来自缓存?

    Hibernate 使用特定的类别来记录所有二级缓存活动。相关类别是org.hibernate.cache,只需在日志框架的配置中为其启用debug

    Chapter 3.5 Logging

    【讨论】:

    • 我不想在日志中运行它 - 我想在将打印到屏幕的测试页面中运行它:公司已缓存/未缓存
    • @Odelya:也许,但你不是 OP :) 如果这个问题不能满足你的需求,请发布一个更具体的问题。
    • 嗨!我和 Riki 在同一个团队。我无法更改她的问题:( 她写了需要检查系统中的对象是否被缓存的页面。但我们不想使用日志 - 我们想要打印视图(我们使用 JSF)
    【解决方案2】:

    试试HitCount and/or MissCount API。

    这样的.....

    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");
    }
    

    【讨论】:

    • 我试过这个代码,但是misscount和hit count总是返回0...我可能犯的任何错误??
    • @Anand 你确定你已经启用了 hibernate.cache.use_second_level_cache、hibernate.cache.use_query_cache、hibernate.generate_statistics? docs.jboss.org/hibernate/core/3.3/reference/en/html/…
    • 如何找出实体的区域名称(rName)?
    • String[] 名称 = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheRegionNames(); for (String name : names) { logger.debug("Entity/Region Name: " + name); }
    【解决方案3】:

    开启缓存日志记录。

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 2010-11-16
      • 2014-11-28
      • 2011-12-18
      • 2012-12-12
      • 2016-05-10
      • 2014-03-15
      • 2010-10-16
      • 2011-07-22
      相关资源
      最近更新 更多