hibernate的二级缓存详解

Hibernate二级缓存

在一个数据库系统中,如果缓存设置的合适,那么可以极大的提高系统的效率,Hibernate作为一个ORM工具
提供了缓存的机制,包括一级(Session级)缓存和二级(SessionFactory级)缓存。这里主要总结一下二级缓存。

1.首先需要在hibernate.cfg.xml中配置,当然需要导入缓存的jar包

< property  name ="hibernate.cache.use_query_cache" > true </ property >
< property  name ="hibernate.cache.provider_class" > org.hibernate.cache.EhCacheProvider </ property >


    hibernate.cache.use_query_cache必须配置,如果想缓存使用findall()、list()、Iterator()、createCriteria()、
    createQuery()等方法获得的数据结果集。

2.在每个实体的hbm文件中配置cache元素,usage可以是read-only或者是read-write等。
   
  < hibernate-mapping >
        
< class  name ="com.xxx.db.base.City"  table ="city"  catalog ="haosou" >
            
< cache  usage ="nonstrict-read-write" />
            
< id  name ="citycode"  type ="string" >
                
< column  name ="citycode"   />
                
< generator  class ="assigned"   />
            
</ id >
            
< property  name ="city"  type ="string" >
                
< column  name ="city"  not-null ="true"   />
            
</ property >
            
< set  name ="districts"  table ="district"  cascade ="all"  inverse ="true" >
                
< key  column ="citycode"   />
                
< one-to-many  class ="com.haosou.db.base.District" />
            
</ set >
        
</ class >
    
</ hibernate-mapping >

如果相对具体某个类的缓存进行特定的配置,需要在ehcache.xml进行配置:

< cache  name ="org.qiujy.domain.cachedemo.Category"   
         maxElementsInMemory
="100"   
         eternal
="true"   
        timeToIdleSeconds
="0"   
        timeToLiveSeconds
="0"   
         overflowToDisk
="false"   
         
/>            

3.Query或Criteria()时设置其setCacheable(true);

    Session session  =  HibernateSessionFactory.getCurrentSession();
    Query q 
=  session.createQuery( " from City " );
    q.setCacheable(
true );
    
return  q.list();
    
    Session session 
=  HibernateSessionFactory.getCurrentSession();
    Query q 
=  session.createQuery( " from District d where d.city.citycode=' "   +  cityId  +   " ' " );
    q.setCacheable(
true );
    
return  q.list();


    执行以上代码时,第一次会查询数据库,但是后面就直接从缓存中查询,而不会使用数据库的连接,提高了性能。
    以上任一环节都不能少,比如cache元素没有配置,那么就会导致查询district的时候发起N个数据库的连接,这样会极大的降低性能。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值