1:ehcache.xml的配置
<ehcache> <!-- 当缓存超出最大值时 应该序列化到硬盘 的路径 --> <diskStore path="f:/ehcache"/> <!-- 这是默认的 --> maxElementsInMemory="10000" 缓存中允许存放的最大对象的数量 eternal="false" 缓存中的数据是否为常量 timeToIdleSeconds="120" 存放数据钝化的时间 timeToLiveSeconds="120" 存放数据的生存时间 overflowToDisk="true"内存不足时是否启用磁盘缓存 diskPersistent="true" 表示当sessionFactory关闭的时候,是否清除硬盘上保存的对象的数据。 <!-- 这是自定义的 --> <cache name="user" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" diskPersistent="true" /> </ehcache>
2:hibernate.cfg.xml的配置
<!-- 二级缓存的实现类--> <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <!-- 配合是否使用查询缓存 --> <property name="cache.use_query_cache">true</property> <!-- 到底哪些持久化类需要启用二级缓存 usage是缓存同步访问策略,region表示使用的缓存区域,与ehcache中的配置要一致 如果不配置region,就表示使用默认的缓存区域 --> <class-cache class="com.lovo.po.Pet" usage="read-write" region="user" />
3:测试类
session.createQuery("select p from Pet p")
.setCacheable(true) //启用
.setCacheRegion("user")
.list();