在使用hibernate二级缓存的时候发现配置的顺序不同就会报错
正确配置顺序:
<!-- 配置隔离级别 -->
<property name="hibernate.connection.isolation">4</property>
<!-- 配置当前线程绑定session -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<!-- <property name="hibernate.cache.use_query_cache">true</property> -->
<!-- 二级缓存供应商 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 配置映射文件 -->
<mapping resource="com/heima/ehcache/domain/Category.hbm.xml"/>
<!-- 指定哪个持久化类使用二级缓存 -->
<class-cache usage="read-only" class="com.heima.ehcache.domain.Category"/>
<!-- <collection-cache usage="read-only" collection=""/> -->
上面是正确的配置顺序:
开启缓存配置--->配置二级缓存使用的第三方实现类(供应商)--->配置映射文件--->指定使用二级缓存的实体类
下面演示错误配置顺序的报错:
错误的配置顺序1:
<!-- 配置映射文件 -->
<mapping resource="com/heima/ehcache/domain/Category.hbm.xml"/>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<!-- <property name="hibernate.cache.use_query_cache">true</property> -->
<!-- 二级缓存供应商 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 指定哪个持久化类使用二级缓存 -->
<class-cache usage="read-only" class="com.heima.ehcache.domain.Category"/>
<!-- <collection-cache usage="read-only" collection=""/> -->
报错信息:
错误配置顺序2:
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<!-- <property name="hibernate.cache.use_query_cache">true</property> -->
<!-- 二级缓存供应商 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 指定哪个持久化类使用二级缓存 -->
<class-cache usage="read-only" class="com.heima.ehcache.domain.Category"/>
<!-- <collection-cache usage="read-only" collection=""/> -->
<!-- 配置映射文件 -->
<mapping resource="com/heima/ehcache/domain/Category.hbm.xml"/>
报错信息:
最后贴出我的测试代码:
1 ehcache.xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="c:/ehcache"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="1200"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
2、测试代码:
@Test
public void testSecondLevelCache(){
Session session1 = HibernateUtils.openSession();
Transaction tx = session1.beginTransaction();
Category c1 = session1.get(Category.class, 1);
System.out.println(c1);
tx.commit();
session1.close();
System.out.println("-------------------------------------------------");
Session session2 = HibernateUtils.openSession();
Transaction tx2 = session2.beginTransaction();
Category c2 = session2.get(Category.class, 1);
System.out.println(c2);
tx2.commit();
session2.close();
}