无为清净楼资源网 Design By www.qnjia.com
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 可以有以下几个取值:
- CacheConcurrencyStrategy.NONE:不使用缓存,默认;
- CacheConcurrencyStrategy.READ_ONLY:只读模式,若对缓存的数据进行修改操作会抛出异常;
- CacheConcurrencyStrategy.NONSTRICT_READ_WRITE:不严格的读写模式,不会对缓存的数据加锁;
- CacheConcurrencyStrategy.READ_WRITE:读写模式,在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询;
- CacheConcurrencyStrategy.TRANSACTIONAL:事务模式,支持事务,当事务发生回滚时,缓存中的数据也回滚,只支持 JPA 。
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>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《星舰铳犬太阳系物语》游戏背景介绍
- 《战锤40K星际战士2》终极版有后续DLC说明
- 《第9层》游戏特色玩法介绍
- 刀郎.2006-刀郎【九雨天下】【WAV+CUE】
- 59.9高校生.1994-素兰万岁【上华】【WAV+CUE】
- ECHO.1991-你是爱我还是需要我(国专)【EMI百代】【WAV+CUE】
- 交错战线零课主线困难通关阵容推荐一览
- 交错战线挖掘矿场角色推荐攻略
- 命运圣契公测平民阵容怎么搭配 新手开荒平民阵容攻略
- 金梅《现代发烧的声音2》发烧碟[WAV+CUE]
- 雨果唱片-《历史录音珍藏系列-现代芭蕾舞剧·红色娘子军》2CD【WAV】
- [雨果唱片]李冰《地方民歌·戏曲系列-爱的颂歌》WAV
- 《模拟人生》真人电影官宣!玛格特·罗比担任制片人
- 《星战绝地》系列玩家数超4000万!续作表现超预期
- EA称AI是其业务核心!能提高开发效率、节约成本