spring 整合 hibernate 时启用二级缓存实例详解
写在前面:
1. 本例使用 hibernate3 + spring3;
2. 本例的查询使用了 hibernatetemplate;
1. 导入 ehcache-x.x.x.jar 包;
2. 在 applicationcontext.xml 文件中找到 sessionfactory 相应的配置信息并在设置 hibernateproperties 中添加如下代码:
<!-- 配置使用查询缓存 --> <prop key="hibernate.cache.use_query_cache">true</prop> <!-- 配置启用二级缓存 --> <prop key="hibernate.cache.use_second_level_cache">true</prop> <!-- 配置二级缓存的提供商 --> <prop key="hibernate.cache.provider_class">org.hibernate.cache.ehcacheprovider</prop>
3. 由于查询使用了 hibernatetemplate,所以还要在 hibernatetemplate 中做相应配置,找到 hibernatetemplate 的配置项,添加如下代码:
<!-- 使用查询缓存 --> <property name="cachequeries"> <value>true</value> </property>
4. 在要缓存的实体类中加入如下注解:
@cache(usage = cacheconcurrencystrategy.read_write)
注:
usage 可以有以下几个取值:
5. 配置 ehcache.xml 文件:
<ehcache> <!-- 指定一个文件目录,当ehcache把数据写到硬盘上时,将把数据写到这个目录下 --> <diskstore path="java.io.tmpdir"/> <!-- name 设置缓存的名字,他的取值为类的完整名字或者类的集合的名字; maxelementsinmemory 设置基于内存的缓存可存放的对象的最大数目 eternal 如果为true,表示对象永远不会过期,此时会忽略timetoidleseconds和timetoliveseconds,默认为false; timetoidleseconds 设定允许对象处于空闲状态的最长时间,以秒为单位; timetoliveseconds 设定对象允许存在于缓存中的最长时间,以秒为单位; overflowtodisk 如果为true,表示当基于内存的缓存中的对象数目达到maxelementsinmemory界限,会把溢出的对象写到基于硬盘的缓存中; --> <!-- 设置缓存的默认数据过期策略 --> <defaultcache maxelementsinmemory="1000" eternal="false" timetoidleseconds="1200" timetoliveseconds="1200" overflowtodisk="false" /> <!-- 设定具体的第二级缓存的数据过期策略 --> <cache name="com.shawearn.model.user" maxelementsinmemory="1000" eternal="false" timetoidleseconds="3000" timetoliveseconds="3000" overflowtodisk="false" /> </ehcache>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
如对本文有疑问, 点击进行留言回复!!
springmvc之ResponseBody响应json数据遇到的错误及解决
uni-app 后台升级 静默升级 uniapp 后台更新 静默更新 在线升级
SpringBoot多Module启动报错Could not transfer metadata
Hibernate项目报错:Cannot call sendError() after the response has been committed
网友评论