一级缓存

一级缓存在session内部,又称为session缓存/事务缓存,随着session的关闭而消失。

原理

session缓存会通过主键查找对应记录,如果缓存中没有,则从数据库加入缓存。

管理

一级缓存作用于太小,不能自定义配置。

常用方法

常用方法 功能
clear() 清空缓存
flush() 刷新缓存,同步数据库
setReadOnly() 设为只读

二级缓存

二级缓存由SessionFactory管理,是整个应用程序的缓存。Hibernate自带的二级缓存很鸡肋,常用第三方二级缓存。

适用范围

  • 缓存适合经常读取,修改不平凡的数据。
  • 不适合经常修改、高并发、数据共享的数据。
  • 应合理设计缓存,提高缓存命中率,减小缓存大小。

## EHCache

EHCache支持只读、不严格读写、读写、将缓存写入文件等。

配置

  1. hibernate.cfg.xml中设置cache.provider_class

    1
    2
    3
    4
    5
    6
    7
    8
    <session-factory>
            <!--EhCacheProvider已弃用,改用EhCacheRegionFactory
            <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
            -->
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.internal.SingletonEhcacheRegionFactory</property>
            <!--使用查询缓存-->
            <property name="hibernate.cache.use_query_cache">true</property>
    </session-factory>
  2. 添加ehcache.xml配置文件,设置ehcache的参数

    1
    2
    3
    4
    5
    <ehcache>
        <diskStore path="java.io.tmpdir"/>
        <defaultCache maxElementInMemory="10000" maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="120" overflowToDisk="true"/>
        <cache name="POJO类(含包名)" ...(参数同defaultCache)/>
    </ehcache>
    参数 说明
    diskStore 当缓存的数量超过maxElementInMemory时,将缓存保存成文件到该目录。java.io.tmpdir表示相对路径自动生成
    defaultCache 默认缓存参数
    maxElementInMemory(已失效) 内存中可缓存的数量(弃用)
    maxEntriesLocalHeap 内存中可缓存的数量。 详见Ehcache(04)——设置缓存的大小
    maxElementsOnDisk 硬盘最大缓存个数
    eternal true表示永不过期,则超时设置无效
    timeToIdleSconds 过期之前的最大空闲时间,单位秒
    timeToLiveSeconds 过期之前的最大生存时间,单位秒
    overflowToDisk 缓存数量超过maxElementInMemory时,是否将缓存写入硬盘
    cache 为具体类设定具体参数,当没有该类没有设定cache时,使用defaultCache。
  3. 修改表映射文件,使用缓存

    添加<cache usage=类型/>

    • usage可选类型为:read-only、read-write、nonstrict-read-write(EnCache不支持transactional)
    • 可选region,默认为本类名,也可指定为cache的name
    • cache标签可放在class下,也可在集合下。当在集合下时,若集合增删则该缓存失效。

管理

常用方法 功能
evict(Class) 移除该实体类的所有缓存
evict(Class, key) 移除该实体类中Object指定主键的缓存
evictCollection(Collection) 移除该集合中的所有元素的缓存
evictEntity(String) String是实体类的类名,功能同evict