现在的位置: 首页 > 综合 > 正文

Hibernate二级缓存的管理

2013年10月03日 ⁄ 综合 ⁄ 共 783字 ⁄ 字号 评论关闭

类似于一级缓存,Hibernate同样提供了方法来操作SessionFactory的二级缓存所缓存的实体:

SessionFactory提供了一个getCache( )方法,该方法的返回值是Cache对象,通过该对象即可操作二级缓存中的实体、集合等。例如如下代码片段:

Cache cache=sessionFactory.getCache();
cache.evictEntity(News.class,id);//清除指定的News对象
cache.evictEntityRegion(News.class);//清除所有News对象
cache.evictCollection("News.actors",id);//清除指定id的News所关联的参与者集合属性
cache.evictCollectionRegion("News.actors");//清除所有News所关联的参与者集合属性

为了更好地统计二级缓存中的内容,可以借助于Hibernate的统计API。

为了开启二级缓存的统计功能,需要在hibernate.cfg.xml文件中进行配置。

 <property name="hibernate.generate_statistics">true</property>
 <property name="hibernate.cache.use_structured_entries">true</property>

接下来即可通过如下方式来查看二级缓存的内容:

private void stat(){
Map cacheEntries=sessionFactory.getStatistics().
    getSecondLevelCacheStatistics("db.domain.News").getEntries();
System.out.println(cacheEntries);
}

抱歉!评论已关闭.