hibernate启用二级缓存

今天看了公司的项目,使用了hibernate开源框架,发现项目中好多配置数据(黑名单等)都是保存在static变量中,个人认为可使用hibernate的二级缓存来存储!

启用二级缓存步骤简介如下:

一、在hibernate.cfg.xml中启用二级缓存(参阅%HIBERNATE_HOME%\project\hibernate-ehcache\src\test\resources\hibernate-config\hibernate.cfg.xml配置文件)
<property name="hibernate.cache.use_query_cache">true</property>
		<property name="cache.use_second_level_cache">true</property>
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>


备注:从以上配置中看出是使用EHCache进行缓存管理,需将ehcache.xml放置到class路径中并导入jar包hibernate-ehcache-4.1.7.Final.jar、ehcache-core-2.4.3.jar、slf4j-api-1.6.1.jar,本次测试用的hibernate版本是hibernate-core-4.1.7.Final.jar

二、指定需要缓存的实体对象(entity.BlackList)
在BlackList.hbm.xml中加入如下配置
<cache usage="read-only"/>


在hibernate.cfg.xml中也可指定需要缓存的实体对象
<class-cache usage="read-only" class="entity.Blacklist"/>

在ehcache.xml中也可指定需要缓存的实体对象
<!-- 库中黑名单有563条记录,所以maxElementsInMemory指定为563 -->
<cache name="entity.Blacklist"
        maxElementsInMemory="563"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        />
可以看出在ehcache.xml中配置灵活性比较好!

补充:使用session.getSessionFactory().getCache().evictXXX()可清空指定的缓存

Hibernate+EhCache配置二级缓存

Hibernate4.1.4配置二级缓存EHCache步骤

张卫_Struts2.3.4_Hibernate4.1.4_Spring3.1.1视频教程源码、笔记下载

在Spring、Hibernate中使用Ehcache缓存

Ehcache 整合Spring 使用页面、对象缓存

猜你喜欢

转载自songjianyong.iteye.com/blog/1944373