2011-06-28 169 views
1

我正在使用Hibernate 3.3.4.GA.在我们的hibernate.cfg.xml文件,我们指定...休眠:麻烦启用二级缓存

<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property> 
    <property name="hibernate.cache.use_query_cache">true</property> 
    <property name="hibernate.cache.use_second_level_cache">true</property> 
    <property name="hibernate.cache.provider_configuration">classpath:ehcache.xml</property> 
    <property name="hibernate.show_sql">true</property> 
    <property name="hibernate.format_sql">true</property> 
    <property name="hibernate.use_sql_comments">true</property> 
    <property name="hibernate.generate_statistics">true</property> 
    <property name="hibernate.cache.use_structured_entries">true</property> 

但在零命中计数和零命中次数,这完全是混淆执行测试对DB(从JUnit的)结果...

@Test 
public void testCache() { 
    final String cacheRegion = WebLead.class.getCanonicalName(); 
    final SecondLevelCacheStatistics settingsStatistics = sessionFactory.getStatistics().getSecondLevelCacheStatistics(cacheRegion); 

    // Make first query. 
    webLeadsDAO.getLeads(lead); 
    System.out.println("miss count:" + settingsStatistics.getMissCount()); 
    System.out.println("hit count:" + settingsStatistics.getHitCount()); 

    // Make second query, expect this to hit cache. 
    webLeadsDAO.getLeads(lead); 
    System.out.println("after second query, hit count: " + settingsStatistics.getHitCount()); 
} 

下面是我们用于检索结果的方法。任何错过计数和命中数的想法都是零?

@Entity 
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY) 
@Table(name="LEAD") 
public WebLeads getLeads(WebLead webLead) { 
    final Session session = sessionFactory.openSession(); 
    final Criteria crit = session.createCriteria(WebLead.class); 
    crit.setCacheable(Boolean.TRUE); 

    // Find webLeads matching input 
    crit.add(Example.create(webLead)); 
    // Make special exception for primary key since that isn't covered by Example.create 
    if (webLead.getLEAD_ID() != null) { 
     crit.add(Restrictions.eq("LEAD_ID", webLead.getLEAD_ID())); 
    } // if 

    @SuppressWarnings("unchecked") 
    final List<WebLead> results = crit.list(); 
    final WebLeads webLeads = new WebLeads(); 
    webLeads.addAll(results); 

    session.close(); 
    return webLeads; 
} 

显然缓存未启用,但我不明白为什么。 - 戴夫

回答

0

请点击这里查看我的回答对工作的二级缓存配置:

Second Level Cache Configuration

我希望它能帮助。

UPDATE:

试试这个:

Statistics stats = sessionFactory.getStatistics(); 
stats.setStatisticsEnabled(true); 
SecondLevelCacheStatistics cacheStats = stats.getSecondLevelCacheStatistics(cacheRegion); 
+0

我的配置是一样的(除非您禁用统计数据),它仍然是行不通的。为什么错过和命中总是零?如果我们没有击中缓存,不应该错过一些数字吗? – Dave

+0

不要错过ehcache.xml中缓存实体或xml片段的注释吗?这个例子很适合我。我不知道可能是什么问题。 – lepike

+0

我编辑了我的resopnse - 我有注释。我认为缓存工作正常,但统计软件包不是 - 为什么总是返回零点击和失误?你如何启用SecondLevelCacheStatistics? – Dave