Hibernate二级缓存配置

发布时间:2025-12-09 20:44:06 浏览次数:3

hibernate版本4.2.2

1.将hibernate里面lib下的optional里面的cache包导入自己的工程


2.applicationContext.xml配置(交给spring管理)

<!-- 开启二级缓存 --> <prop key="hibernate.cache.use_second_level_cache">true</prop> <!-- 启动"查询缓存"如果想缓存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集,必须配置此项--> <prop key="hibernate.cache.use_query_cache">true</prop> <!-- 设置二级缓存插件EHCache的Provider类--> <!-- hibernate4不再使用 --><!-- <property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> --> <!-- 二级缓存区域名的前缀 --> <!--<property name="hibernate.cache.region_prefix">test</property>--> <!-- 高速缓存提供程序 --> <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <!-- Hibernate4以后都封装到org.hibernate.cache.ehcache.EhCacheRegionFactory --> <!-- 指定缓存配置文件位置 --> <prop key="hibernate.cache.provider_configuration_file_resource_path"> ehcache.xml </prop> <!-- 强制Hibernate以更人性化的格式将数据存入二级缓存 --> <prop key="hibernate.cache.use_structured_entries">true</prop> <!-- Hibernate将收集有助于性能调节的统计数据 --> <prop key="hibernate.generate_statistics">true</prop>

3.cache.xml配置

<?xml version="1.0" encoding="UTF-8"?><ehcache><diskStore path="java.io.tmpdir" /><defaultCache maxElementsInMemory="10000" eternal="false"overflowToDisk="false" timeToIdleSeconds="0" timeToLiveSeconds="0"diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /></ehcache>

4.由于使用的是注解的方式,所以在实体头加入如下注解

@Cacheable@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

5.在查询的方法加入

query.setCacheable(true);
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477