配置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。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值