在 Hibernate中使用ehcache管理二级缓存

EhCache是一个纯JAVA程序,可以在Hibernate中作为一个插件引入。在Hibernate中使用EhCache需要在Hibernate的配置文件中设置如下:

 

<!-- 开启二级缓存 --> <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>
 

 

设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <diskStore path="c:\\cache"/>  <!--设置cache.data文件存放位置-->
  <defaultCache
   maxElementsInMemory="10000" <!-- 缓存最大数目 -->
   eternal="false" <!-- 缓存是否持久 -->

   overflowToDisk="true" <!-- 是否保存到磁盘,当系统当机时-->

   timeToIdleSeconds="300" <!-- 当缓存闲置n秒后销毁 -->
   timeToLiveSeconds="180" <!-- 当缓存存活n秒后销毁-->
   diskPersistent="false"
   diskExpiryThreadIntervalSeconds= "120"/> <!--设定缓存在硬盘上的生存时间-->
</ehcache>

 

 

注意当eternal="true"

timeToIdleSecondstimeToLiveSecondsdiskExpiryThreadIntervalSeconds都是无效的。

 

此时缓存已经启用了,但是并没有被使用。它不会去自动把所有的实体都进行缓存了,而是需要手动指定哪个实体需要缓存,以及其缓存的策略。有两种方式指定哪些实体类使用缓存。

 

第一种是修改要使用缓存的实体的映射文件。如在User.hbm.xml中使用<cache>标签启用。

 

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

 

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

<!-- 指定哪些实体需要使用二级缓存 -->

<class-cache class="com.pojo.User" usage="read-only"/>

 

 

如果需要“查询缓存”,还需要在使用QueryCriteria()时设置其setCacheable(true);属性

Session s=HibernateSessionFactory.getSession();  

Criteria c=s.createCriteria(Resources.class);  

c.setCacheable(true);  

List l=c.list();

……

 

配置log4j.properties文件

#方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。
log4j.logger.org.hibernate.cache=debug

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值