hibernate二级缓存

缓存机制

缓存:介于应用程序和永久存储介质(硬盘、U盘、磁带、刻录CD)之间、其作用是降低应用程序和硬盘介质的直接读写频率。从而提升应用程序的性能、缓存一般在内存在。

数据库缓存:减少与数据库间的频繁操作。可以大大提升数据访问速度。

二级缓存

hibernate 中一级缓存就是session级别的缓存、在同一次请求中共享数据。
hibernate 中二级缓存就是sessionFactory、整个应用程序共享一个会话工厂、共享一个二级缓存。

sessionFactory缓存分为两部分:
1、内置缓存:内部会使用一个缓存、用于 存储配置信息、存储预定义HQL语句。只读。
2、外置缓存 : 用于存储用户自定义数据、默认未开启、外置缓存hibernate只提供了规范(接口)、并为实现、需要借助第三方类。可读写。

二级缓存、可以缓存的内容

1、类级别缓存
2、集合级别缓存
3、时间戳缓存
4、缓存查询结果

缓存的级别

1、事务级缓存(translation)、性能低。
2、读写型缓存 ( read-write )、适用经常读、很少写的环境。更新时会锁定缓存中数据。
3、只读型缓存 ( read-only )、从来不会被修改、做更新会出现异常。
4、非严格读写 (nonstrict-read-write )、更新时不锁定数据、容易造成脏读写。
注意:2、3 较为常用。
适合放入二级缓存的数据: 很少被修改的数据、不重要的数据

二级缓存常见的供应商(第三方缓存技术)

1、ehcache 支持集群、不支持事务级缓存
2、Jbosscache
3、swamecache
4、openSymphony

继承步骤
  • 1、导入jar包

    • ehcache-2.10.3.jar
    • hibernate-ehcache-5.2.10.Final.jar
    • slf4j-api-1.7.7.jar
  • 2、在applicationContext.xml中添加以下配置

      <!-- 开启二级缓存 -->
      <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.SingletonEhCacheRegionFactory
      </prop>
    
  • 3、配置ehcache.xml 说明缓存

      <?xml version="1.0" encoding="UTF-8"?>
      <ehcache>
      <!-- 配置文件缓存溢出后存储位置 -->
      <diskStore path="c:/ehcache"></diskStore>
      <!--
      	maxElementsInMemory : 缓存的最多个数
      	eternal : 对象永久有效、一旦设置为true、那么timeout就无效
      	timeToIdleSeconds : 设置对象失效前空闲的最大时间、当设置eternal="false"、才能起效
      	timeToliveSeconds : 设置对象失效前可以存活多少秒、设置0、表示永久有效
      	overflowToDisk : 溢出时写入硬盘
       -->
      <defaultCache maxElementsInMemory="100000" eternal="false" 
      	timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"/>
      </ehcache>
    
  • 4、在hbm.xml文件中开启缓存

      <!-- 开启缓存 -->
      <cache usage="read-write"/>
    
  • 5、查询缓存、要在代码中设置开启二级缓存

  • 1.)

      this.getHibernateTemplate().setCacheQueries(true)
    
  • 2.)使用此方式数据访问成的Bean就要注入 hibernateTemplate 了

      <!-- spring4.0托管hibernate5通过HibernateTemplate -->
      <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
      	<property name="sessionFactory" ref="sessionFactory"></property>
      	<property name="cacheQuery" value="true"></property>
      </bean>
    
    
      <bean id="movieDao" class="cn.com.dao.impl.MovieDaoImpl">
      	<property name="hibernateTemplate" ref="sessionFactory"></property>
      </bean>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值