项目经验记录:spring整合hibernate,配置二级缓存

最近用SSH帮老师做个项目,涉及到一些表的查询,而这些表的字段相对较多,每次查询都是执行SQL语句访问数据库,这样子就导致每次查询的速度很慢。所以我想到了用hibernate的二级缓存机制,至于hibernate二级缓存详细的原理可以百度找博客了解,这里就不多累赘。

spring整合hibernate配置二级缓存步骤:

1.配置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">  
    <!-- DISKStury路径必须配置,不然报错 -->
    <diskStore path="D:\\mytemp"/>  
    <!-- 数据过期策略 -->  
    <defaultCache  
        maxElementsInMemory="10000" 
        eternal="false"  
        timeToIdleSeconds="600"  
        timeToLiveSeconds="600"  
        overflowToDisk="true"  
        />  
    <!-- 具体到某个类的数据过期策略 -->  
    <!-- <cache name="com.lanhuigu.hibernate.entity.Customer"  
        maxElementsInMemory="10000"  
        eternal="false"  
        timeToIdleSeconds="300"  
        timeToLiveSeconds="600"  
        overflowToDisk="true"  
        />   -->

</ehcache>  

2.在spring中整合hibernate二级缓存

2.1<!-- 配置SessionFactory创建 -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
       
   <!-- 指定hibernate核心配置文件 -->
   <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
    <property name="hibernateProperties">  
            <props>   
                <!-- 是否开启二级缓存 -->  
                <prop key=" hibernate.cache.use_second_level_cache">true</prop>  
                <!-- 是否启用查询缓存 -->  
                <prop key=" hibernate.cache.use_query_cache">true</prop>  
                <!-- 配置二级缓存提供商 --> 
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>  
                 <!-- 配置 ehcache.xml的路径-->
                <prop key="hibernate.net.sf.ehcache.configurationResourceName">classpath:ehcache.xml</prop>  
            </props>  
        </property>  

   </bean>

2.2为hibernateTemplate打开缓存查询

<!-- 配置HibernateTemplate -->
   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
       <!-- 注入sessionFactory -->
      <property name="sessionFactory" ref="sessionFactory"></property>
       <property name="cacheQueries" value="true"/>

  </bean>

3.指定哪些实体类加入缓存

只需在实体类映射的hbm.xml文件中加入:  <cache usage="read-write"/><!-- 配置缓存策略 -->

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值