hibernate 缓存

一,session缓存

   默认的不可配置

二,SessionFactory缓存

   分两种

    1,hibernate自带的缓存不可配置,hibernate启动时加载的,cfg.xml文件就属于这种

    2,可以配置hibernate缓存,外置缓存 需要缓存插件,如EHcache

     步骤:

      1,添加 相关的jar 包,ehcache.xml文件

      2,配置***.cfg.xml文件

        .启用二级缓存

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

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

           <property name="hibernate.cache.region.factory_class">

            org.hibernate.cache.ehcache.EhCacheRegionFactory

          </property>

        .启用查询缓存

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

        .如果某个entity或者其属性要用到二级缓存 还要设置

          <class-cache usage="read-write" class="com.m01.joinedsubclass.Animal"/>

           配置时精确到类的属性dogs

          <collection-cache usage="read-only" collection="com.m01.joinedsubclass.Animal.dogs"/>

          当然也可以在该entity对应的映射文件中配置


ehcache.xml文件 

  属性:  <diskStore path="C:\ehcache"/>

      设置缓存数据存储在硬盘是的位置

  属性:

     <defaultCache
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      overflowToDisk="true"
      />

    设置默认的缓存数据策略

  属性:

    <cache name="com.m01.joinedsubclass.Animal"
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="300"
      timeToLiveSeconds="600"
      overflowToDisk="true"
      />

    设定具体的命名缓存的数据过期策略,每个命名缓存代表一个缓存区域。如果没有给相应的对象设置相应命名缓存

    那么该对象将使用默认的缓存数据策略;hibernate在不同的缓存区域保存不同的类/集合,对于类而言,缓存区域的名称是全类名

    对于集合而言,缓存区域的名称 是全类名+属性名。

    maxElementsInMemory : 设置该内存空间中存放的最多对象的数目

    eternal:设置对象是否永久有效 ,true表示永不过期,此时timeToIdleSeconds和timeToLiveSeconds 属性 不管用

    timeToLiveSeconds : 设置对象生存的最长时间 设置值要大于timeToIdleSeconds 设置值

    timeToIdleSeconds : 设置对象最大空闲时间,过期则被清除。

    overflowToDisk : 设置当内存中的对象数目达到最大值后,是否将其余对象保存到指定的硬盘中

原文地址:https://www.cnblogs.com/m01qiuping/p/6390999.html