hibernate的二级缓存

Hibernate二级缓存也称为进程级的缓存或SessionFactory级的缓存。二级缓存是全局缓存,它可以被所有的session共享。二级缓存的生命周期和SessionFactory的生命周期一致,SessionFactory可以管理二级缓存。
二级缓存的配置使用:
1.在crc下创建echcache.xml文件,其内容如下:

<ehcache> 
<diskStore path="java.io.tmpdir"/> 
<defaultCache maxElementsInMemory="10000" eternal="false" 
overflowToDisk="true" timeToIdleSeconds="120"
 timeToLiveSeconds="120" diskPersistent="false" /> 
</ehcache>

maxElementsInMemory属性用于指定缓存中最多可放多少个对象。
eternal属性指定缓存是否永久有效。
timeToIdleSeconds属性指定缓存多久未被使用便清理掉。
timeToLiveSeconds属性指定缓存的生命长度。
diskPersistent属性指定缓存是否被持久化到硬盘中,保存路径由<diskStore>标签指定。
2.修改hibernate.cfg.xml文件开启二级缓存。

<hibernate-configuration> 
<session-factory> 
<!-- 开启二级缓存 --> 
<property name="hibernate.cache.use_second_level_cache">true</property> 
<!-- 设置缓存提供者 --> 
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property> 
<mapping resource="cn/ineeke/entity/User.hbm.xml"/> 
</session-factory> 
</hibernate-configuration>

3.指定哪些实体类使用缓存。经过第二步缓存是启用了,但是并没有被使用。它不会去自动把所有的实体都进行缓存了,而是需要手动指定哪个实体需要缓存,以及其缓存的策略。这里有两种方式,第一种是修改要使用缓存的实体的映射文件。如在User.hbm.xml中使用<cache>标签启用。

<hibernate-mapping> 
<class name="cn.ineeke.entity.User" table="t_user"> 
<cache usage="read-only"/> 
<id name="id"> 
<generator class="native"/>
 </id> 
<property name="name"/> 
</class>
 </hibernate-mapping>

第二种方式是在hibernate.cfg.xml中使用<class-cache>标签指定实体类并启用。

<hibernate-configuration> 
<session-factory>
 <!-- 开启二级缓存 --> 
<property name="hibernate.cache.use_second_level_cache">true</property>
 <!-- 设置缓存提供者 --> 
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider</property>
 <mapping resource="cn/ineeke/entity/User.hbm.xml"/> 
<!-- 指定哪些实体需要使用二级缓存 --> 
<class-cache class="cn.ineeke.entity.User" usage="read-only"/> 
</session-factory>
 </hibernate-configuration>

   <calss-cache>标签中的class属性指定要对哪个实体进行缓存,而usage属性与<cache>标签的相同,都指的是缓存策略,此值依实际需要而定,默认采用read-only。

猜你喜欢

转载自svsesunyuan.iteye.com/blog/1026030