hibernate ehcache二级缓存

时间:2023-03-08 17:23:52
hibernate   ehcache二级缓存

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- Sets the path to the directory where cache .data files are created.
设置缓存文件保存的目录
The following properties are translated:
user.home - User's home directory
如果设置user.home则目录是:C:\Users\Administrator
user.dir - User's current working directory - 当前项目的工作目录
java.io.tmpdir - Default temp file path
系统的临时目录:
-->
<diskStore path="d:/a"/>
<!-- 以下是配置默认的缓存,如果没有指定哪一个类,缓存的哪一个文件中,则都使用默认的缓存策略 -->
<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory
设置在内存中最多可以保存多少个对象
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired. 如果设置为true,则一个对象保存在内存中永远不过期
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
设置一个空闲时间=现在的时间 - 最后访问时间
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
TTL = 当前时间- 创建时间
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
memoryStoreEvictionPolicy 保存策略:
FIFO- First In First Out
LFU - Less Frequtly Use
LRU less Recently(最近) Use -->
<defaultCache
maxElementsInMemory=""
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="true"
memoryStoreEvictionPolicy="FIFO"
/>
</ehcache>

在hibernate.cfg.xml中配置

<!-- 配置打开二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 提供二缓存的类 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

配置对哪个类进行二级缓存

<!-- 对某个类进行二级缓存 -->
<class-cache usage="read-write" class="cn.domain03.Book"/>

实例

<mapping resource="cn/domain03/Book.hbm.xml"/>
<!-- 对某个类进行二级缓存 -->
<class-cache usage="read-write" class="cn.domain03.Book"/>