类似于一级缓存,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);
}
本文介绍了Hibernate中如何使用SessionFactory的getCache()方法操作二级缓存中的实体和集合,并展示了如何配置和利用统计API来监控二级缓存的状态。
273

被折叠的 条评论
为什么被折叠?



