Spring环境下Hibernate二级缓存的应用

在数据不经常变化的地方,为了能够提高网站系统的执行效率,使用缓存是我们经常想到的解决方式。Hibernate的缓存分为三类,我们在平时应用开发中,最容易忽略的就是它的一级缓存,因为它的生命周期与session一致。二级缓存的应用是最普遍的,也是行之有效的。那么怎么配置它呢?主要分为以下几步:

《1》搭建Spring+Hibernate环境

《2》加载Hibernate-ehcache相应的jar包

《3》在applicationContext.xml中添加缓存的相关配置:

         <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" ></property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/entity/test</value>
</list>
</property>
<property name="hibernateProperties">
   <props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">false</prop> 
<!-- 开启hibernate的查询缓存 -->
       <prop key="hibernate.cache.use_query_cache">true</prop>
       <!-- 开启hibernate二级缓存-->
       <prop key="hibernate.cache.use_second_level_cache">true</prop>
       <!-- hibernate缓存管理类-->
       <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                        <!-- hibernate缓存配置文件-->
       <prop key="hibernate.cache.configurationResourceName">ehcache.xml</prop>
  </props>
</property> 
</bean>

《4》在src目录下创建ehcache.xml缓存文件,内容大致如下:

       <?xml version="1.0" encoding="UTF-8"?>
       <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
          <diskStore path="java.io.tmpdir" />
          <defaultCache eternal="false" 
                                 maxElementsInMemory="1000"
                                 overflowToDisk="false" 
     diskPersistent="false" 
     timeToIdleSeconds="0"
    timeToLiveSeconds="600" 
     memoryStoreEvictionPolicy="LRU" />

   <cache name="departCache" 
        eternal="false"
         maxElementsInMemory="100"
         overflowToDisk="false"
         diskPersistent="false" 
        timeToIdleSeconds="0"
         timeToLiveSeconds="300"
         memoryStoreEvictionPolicy="LRU" />

</ehcache>

其中具体的含义可以参考网上的定义,这里不再标注。

《5》在dao中引入二级缓存:
             
HibernateTemplate template = this.getHibernateTemplate();     
     template.setCacheQueries(true);//开启hibernate二级缓存     
     List result =  template.find(sql);   
     template.setCacheQueries(false);     


总结:初次查询会连接数据库,其后会从缓存中返回结果,而不会继续从数据库中读取。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值