Spring 整合 Hibernate 时启用二级缓存实例详解
技术  /  管理员 发布于 8年前   193
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>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
