为Hibernate配置二级缓存,当第一次从数据库读取文件后其会在指定的文件夹位置进行缓存。这样利于读取数据。
下面开始配置二级缓存:
1.在Spring的beans.xml加入以下几句代码:
<!-- 解决问题是加入了二级缓存的配置 -->
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
2.在bean的映射文件中加入配置缓存文件代码:
<cache usage="read-write" region="cn.itcast.bean.Person"/>
3.在类路径下配置ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="D:\cache"/>
<defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="180"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="60"/>
<cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"
overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"></cache>
</ehcache>
@Test
public void testGetPerson() {
System.out.println(personService.getPerson(1).getName());
try {
System.out.println("请关闭数据库");
Thread.sleep(1000*15);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("第二次获取");
System.out.println(personService.getPerson(1).getName());
}
运行,看在关闭数据库后,第二次获取数据能否得到。