二级缓存的实现

来源:互联网 发布:模糊查询sql语句 编辑:程序博客网 时间:2024/05/23 23:00

二级缓存的实现:

1.添加jar包

hibernate-release-4.3.11.Final\lib\optional\ehcache\*.jar

2.添加配置文件

拷贝hibernate-release-4.3.11.Final\project\etc\ehcache.xml到src下

3.开启二级缓存

<property name="cache.use_second_level_cache">true</property>

4.配置使用的二级缓存的产品

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

5.配置对哪些类使用hibernate的二级缓存(二选一)  

4.1在cfg中配置(统一配置)

<class-cache usage="read-write" class="base.many2oneBoth.Emp" />

4.2在类对应的hbm中配置

 

 

 

6.配置对集合使用二级缓存

对集合使用二级缓存(属性全路径) 缓存集合包含对象的所有id

<collection-cache usage="read-write"

collection="base.many2oneBoth.Dept.emps" />

也可以在对应的hbm的set中添加子元素配置

<set name="employees" table="emps">

    <cache usage="read-write"/>

    <key column="DEPT_ID"></key>

    <one-to-many class="Emp"/>

  </set>

配置对集合中每个元素使用二级缓存

<class-cache usage="read-write" class="base.many2oneBoth.Emp" />

 

 

配置文件详解:

<ehcache>

    <!-- 设置当缓存对象益出时,对象保存到磁盘时的保存路径。

            如 d:\xxxx

         The following properties are translated:

         user.home - User's home directory

         user.dir - User's current working directory

         java.io.tmpdir - windows的临时目录 -->

    <diskStore path="java.io.tmpdir"/>

    <!--默认数据过期策略

        maxInMemory       - 缓存中可以存入对象最大个数

        eternal           - true:表示永不失效,false:不是永久有效的。

        timeToIdleSeconds - 空闲时间,当第一次访问后在空闲时间内没有访问,则对象失效,单位为秒

        timeToLiveSeconds - 被缓存的对象有效的生命时间,单位为秒

      overflowToDisk  当缓存中对象数超过核定数(益出时)时,对象是否保存到磁盘上。true:保存;false:不保存

         如果保存,则保存路径在标签<diskStore>中属性path指定

        -->

    <defaultCache

        maxElementsInMemory="10000"

        eternal="false"

        timeToIdleSeconds="120"

        timeToLiveSeconds="120"

        overflowToDisk="true"

        />

<!-- 设定具体的命名缓存数据过期策略

      对于类而言name="base.many2oneBoth.Emp"

      对于集合而言name="base.many2oneBoth.Dept.orders"

-->

<cache name="base.many2oneBoth.Emp"

        maxElementsInMemory="1"

        eternal="false"

        timeToIdleSeconds="1000"

        timeToLiveSeconds="2000"

        overflowToDisk="true"

        />

</ehcache>