Hibernate 二级缓存配置和应用

1.初始化HibernateSessionFactory时增加启用配置

  a.<prop key="hibernate.cache.use_second_level_cache">true</prop>启用二级缓存

  b.<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>二级缓存的支持类

  c.<prop key="hibernate.cache.use_query_cache">true</prop>启用查询缓存

  由于代码是无规则的,各种配置方法都有,但是这三项是不会少的。

2.Hibernate表配置文件设置

  <cache usage="read-only"></cache>只在读取时使用缓存

  还有其他配置如read-write、nonstrict-read-write等等,网上可以查到各种配置详解

3.查询之前一定要设置用缓存查询

  baseOpreteDao.getHibernateTemplate().setCacheQueries(true);

  或者其他不使用dao这种代码方式的,也在找到hibernate中对应设置setCacheQueries(true)类似的地方设置

  这个时候会有几个警告,

4.去掉几个常见警告的配置

  找到ehcache-1.2.3.jar包,解压取出ehcache.xml,放在src目录下

  encache.xml里追加如下几个配置

  <cache name="org.hibernate.cache.StandardQueryCache"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="4200"
        overflowToDisk="true"
        />

  <cache name="org.hibernate.cache.UpdateTimestampsCache"
        maxElementsInMemory="5000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        />

  <cache name="org.appfteaching.model.TArticleclass"
     maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="100"
        timeToLiveSeconds="4200"
        overflowToDisk="true"
    />

  还要追加一个自己bhibernate表对应Class的配置,和上边的配置一样,只要name改成要启用缓存的表的class

 

如上配置后,查询会首先到缓存中查找,没有再去数据库查找,查找结果会加入缓存。缓存起作用时,可以看到从缓存中查找时没有调用数据库的SQL文。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值