Spring+Hibernate下配置Hibernate二级缓存EhCache

假设类A为持久化对象,对应表为tableA,这里没有考虑A和其他表关联的情况。

在spring下配置使用二级缓存:

< property  name ="hibernateProperties" >
< props >
........
< prop  key ="hibernate.cache.provider_class" > ${hibernate.cache.provider_class} </ prop >
< prop  key ="hibernate.cache.use_query_cache" > ${hibernate.cache.use_query_cache} </ prop >
</ props >
</ property >

 其中${hibernate.cache.provider_class}为net.sf.ehcache.hibernate.EhCacheProvider,${hibernate.cache.use_query_cache}属性值为true(对经常使用的List查询方式,只有在使用查询缓存时,才会从缓存中通过id去get缓存的值;查询缓存一般缓存查询语句和查询结果的id)

A的持久化映射文件中加上cache元素:usage属性的取值根据自己的情况自己指定相应的值

< cache usage = " read-write " />

 

配置spring的HibernateTemplate对查询语句和结果缓存(cacheQueries值为true):

< bean  id ="hibernateTemplate"  
        class
="org.springframework.orm.hibernate3.HibernateTemplate" >
                      
< property  name ="sessionFactory" >< ref  bean ="sessionFactory" /></ property >
    
< property  name ="cacheQueries"  value ="${hibernate.cache.use_query_cache}" ></ property >
</ bean >

开发的spring dao(集成HibernateDaoSupport)应该配置实用这个hibernateTemplate:

<bean id="myDao" class="subclass of HibernateDaoSupport">
  <property name="hibernateTemplate" ref="hibernateTemplate" />
  <property name="jdbcTemplate" ref="jdbcTemplate" />
 </bean>

在src下新建ehcache.xml文件,文件内容如下:

< ehcache >
  
< diskStore  path ="java.io.tmpdir" />

  
<!--  
        eternal:元素是否永久的;
        MemoryStoreEvictionPolicy:default is LRU
    
-->
 
< defaultCache          maxElementsInMemory ="10000"
            eternal
="false"             timeToIdleSeconds ="120"             timeToLiveSeconds ="120"
            overflowToDisk
="true"             diskPersistent ="false"            diskExpiryThreadIntervalSeconds ="120"
            memoryStoreEvictionPolicy
="LRU" />

  
< cache  name ="cn.hnisi.persistence.mmedia.Dmtjbxx"
               maxElementsInMemory
="500"                eternal ="false"
               timeToIdleSeconds
="2400"       timeToLiveSeconds ="3600"
               overflowToDisk
="false" />

  
< cache  name ="org.hibernate.cache.StandardQueryCache"  
        maxElementsInMemory
="50"  eternal ="false"  timeToIdleSeconds ="600"  
        timeToLiveSeconds
="1200"  overflowToDisk ="false" />  
  
  
< cache  name ="org.hibernate.cache.UpdateTimestampsCache"  
        maxElementsInMemory
="500"  eternal ="true"  overflowToDisk ="false" />  

</ ehcache >

然后你可以使用HQL查询对象了,比如"from A where name=?";

跟踪查询的sql日志就可以看出第一次是查询数据库,第二次是从缓存中get(见Hibernate ReadWriteCache类的get方法)

问题:什么样的数据适合存放到第二级缓存中?

1 很少被修改的数据
2 不是很重要的数据,允许出现偶尔并发的数据
3 不会被并发访问的数据
4 参考数据,指的是供应用参考的常量数据,它的实例数目有限,它的实例会被许多其他类的实例引用,实例极少或者从来不会被修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值