Hibernate4 二级缓存配置

本文介绍如何在Hibernate中配置和使用二级缓存,包括配置文件的设置、EHCache的使用及映射文件中的缓存策略,并提供了验证方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Hibernate配置文件开启二级缓存
<!--开启二级缓存-->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--指定二级缓存的提供类-->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!--指定二级缓存配置文件的位置-->
<property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>

【注意】

这里使用的是hibernate4.xx版本,如果是hibernate3.xx版本,则二级缓存提供类改为如下配置:

<!--这个类在4.0以后不建议使用-->

<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>


2、配置EHCache缓存,创建ehcache.xml文件,放到项目根目录下,ehcache.xml内容如下

<ehcache updateCheck="false">
	<!-- Sets the path to the directory where cache .data files are created.
    	 If the path is a Java System Property it is replaced by its value in the running VM.
         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path
	-->
	
	<!--指定二级缓存存放在磁盘上的位置-->
	<diskStore path="java.io.tmpdir" />
	<!--<diskStore path="user.dir" />-->
	
	<!--可以每个实体类指定一个对应的缓存,如果没有匹配到该类,则使用这个默认的缓存配置-->
    <!--
		maxElementsInMemory: 在内存中存放的最大对象数;
		eternal: 是否永久保存缓存,设置成false;
		timeToLiveSeconds: 以创建时间为基准开始计算的超时时长;
		timeToIdleSeconds: 在创建时间和最近访问时间中取出离现在最近的时间作为基准计算的超时时长;
		overflowToDisk: 如果对象数量超过内存中最大的数,是否将其保存到磁盘中,设置成true;
		如果仅设置timeToLiveSeconds,则该对象的超时时间=创建时间+timeToLiveSeconds,假设为A;
		如果没设置timeToLiveSeconds,则该对象的超时时间=max(创建时间,最近访问时间)+timeToIdleSeconds,假设为B;
		如果两者都设置,则取出A、B中的较小值,即min(A,B),表示只要有一个超时成立即算超时;
  -->
    <defaultCache 
    	maxElementsInMemory="10000" 
    	eternal="false" 
    	overflowToDisk="true" 
    	timeToIdleSeconds="120" 
    	timeToLiveSeconds="120" 
    	diskPersistent="false" 
    	diskExpiryThreadIntervalSeconds="120" />
	


	<!--可以给每个实体类指定一个配置文件,通过name属性指定,要使用类的全名-->
	<!--<cache name="com.xiaoluo.bean.Student" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />-->
</ehcache>

3、在映射文件 *.hbm.xml 中设置缓存策略

class 节点添加如下配置

<!--缓存策略-->
<cache usage="read-only" />

【提示】二级缓存的策略一般有:read-only、nonstrict-read-write、read-write、transactional。
通常二级缓存都配置成read-only,否则如果对缓存进行读写,性能会变差,缓存就失去了意义。

4、验证Hibernate是否从二级缓存中获取数据
【提示】如果我们只是取出对象的一些属性的话,则不会将其保存到二级缓存中去,因为二级缓存缓存的仅仅是对象。
【提示】在Log4j中加上以下代码可以看到Hibernate从缓存中查询数据,注意,以下配置需要使用slf4j的JAR包
log4j.logger.org.hibernate=debug  


转载: http://www.360doc.com/content/14/0801/16/1073512_398635409.shtml

转载: http://www.cnblogs.com/xiaoluo501395377/p/3377604.html

参考: http://my.oschina.net/alexgaoyh/blog/348188

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值