spring 配置 hibernate 二级缓存

今天在配置spring + hibernate过程中出现些问题,不过最终成功了,拿出来分享一下

 

1:配置spring 文件

在sessionfactiory的bean中加上如下配置

Xml代码
  1. < prop   key = " hibernate .show_sql" > true </ prop >   
  2. 打开二级缓存                 
  3. < prop   key = " hibernate .cache.use_second_level_cache" > true </ prop >   
  4. 指定二级缓存的外部程序我用的是ECACHE   
  5. < prop key = " hibernate .cache.provider_class" > org.hibernate .cache.EhCacheProvider </ prop>     
  6. 打开hibernate 的查询缓存   
  7. < prop   key = " hibernate .cache.use_query_cache" > true </ prop >   

2配置要使用缓存的实体

Xml代码

< hibernate -mapping >   

     < class   name = "com.tjsinfo.tjsoa.mail.vo.TjsEmailFolder"   table = "TjsEmailFolder"   schema ="tjsoadba"   catalog = "TJSOA" >   

关键是这里指定缓存的策略一般用读写就可以了,如果数据从不变化可以用只读   

         < cache   usage = "read-write" > </ cache >   

         < id   name = "folderId"   type = "java.lang.Integer" >   

             < column   name = "Folder_id"   />   

             < generator   class = "native"   />   

         </ id >

    </ class >   

</ hibernate -mapping >

3定义ehcache.xml文件

Xml代码

< ehcache >   

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

<defaultCache maxElementsInMemory="10000" eternal="false"
   timeToIdleSeconds="120" timeToLiveSeconds="120"
   overflowToDisk="false" /></ehcache>

4执行相应的HQL语句,应当是第一次执行有SQL而第二次没有可是我试了一下还是有SQL说明查询缓存没用。我晕。

后来发现应当在调用查询的方法中的spring   的hibernate 模板设置打开查询缓存。

Java代码

public   List selectHql(String hql) {   

         // TODO Auto-generated method stub    

        getHibernateTemplate().setCacheQueries( true );   

         return   getHibernateTemplate().find(hql);   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值