该功能依赖二级缓存,所以必须先配置开启了二级缓存功能!
分两种情况
情况一,项目中有hibernate.cfg.xml配置文件
<!-- 开启二级缓存,使用EhCache缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- 开启收集缓存统计信息的功能,可以查看实际缓存的内容、命中率等 -->
<property name="hibernate.generate_statistics">true</property>
<!-- optionally, force Hibernate to keep the cache entries in a more readable format -->
<property name="hibernate.cache.use_structured_entries">true</property>
情况二,项目集成了Spring框架,没有hibernate.cfg.xml配置文件
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
......
<property name="hibernateProperties">
<props>
......
<!-- 开启二级缓存,使用EhCache缓存 -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<!-- 开启查询缓存 -->
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- 开启收集缓存统计信息的功能,可以查看实际缓存的内容、命中率等 -->
<prop key="hibernate.generate_statistics">true</prop>
<!-- optionally, force Hibernate to keep the cache entries in a more readable format -->
<prop key="hibernate.cache.use_structured_entries">true</prop>
......
</props>
</property>
<property name="mappingResources">
<list>
<value>edu/po/Users.hbm.xml</value>
<value>edu/po/TLog.hbm.xml</value>
</list>
</property>
</bean>
统计信息使用的demo:
//Cache统计统计信息
Statistics statistics= sessionFactory.getStatistics();
System.out.println(statistics);
System.out.println("放入"+statistics.getSecondLevelCachePutCount());
System.out.println("命中"+statistics.getSecondLevelCacheHitCount());
System.out.println("错过"+statistics.getSecondLevelCacheMissCount());
//详细的Cache统计信息
for (int i = 0; i < statistics.getEntityNames().length; i++) {
String entityName = statistics.getEntityNames()[i];
EntityStatistics entityStatistics = statistics.getEntityStatistics(entityName);
StringBuilder cacheOperator = new StringBuilder();
cacheOperator.append("CategoryName:" ).append(entityStatistics.getCategoryName())
.append(",DeleteCount:").append(entityStatistics.getDeleteCount())
.append(",FetchCount:").append(entityStatistics.getFetchCount())
.append(",InsertCount:").append(entityStatistics.getInsertCount())
.append(",LoadCount:").append(entityStatistics.getLoadCount())
.append(",OptimisticFailureCount:").append(entityStatistics.getOptimisticFailureCount())
.append(",UpdateCount:").append(entityStatistics.getUpdateCount());
System.out.println(cacheOperator.toString());
}