深入学习Hibernate4_07使用二级缓存

来源:互联网 发布:linux安装oracle 编辑:程序博客网 时间:2024/06/11 02:31
1. 使用 Hibernate 二级缓存的步骤:

        1). 加入二级缓存插件的 jar 包及配置文件:

               I. 复制 \hibernate-release-4.2.4.Final\lib\optional\ehcache\*.jar 到当前 Hibrenate 应用的类路径下.
              II. 复制 hibernate-release-4.2.4.Final\project\etc\ehcachexml 到当前 WEB 应用的类路径下

        2). 配置 hibernate.cfg.xml

              I.   配置启用 hibernate 的二级缓存        
               <property name="cache.use_second_level_cache">true</property>
             II.  配置hibernate二级缓存使用的产品   
              <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

            III. 配置对哪些类使用 hibernate 的二级缓存   

             <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>

                         实际上也可以在 .hbm.xml 文件中配置对哪些类使用二级缓存, 及二级缓存的策略是什么.

2. 集合级别的二级缓存的配置

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

              <collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/> 也可以在 .hbm.xml 文件中进行配置

<set name="emps" table="GG_EMPLOYEE" inverse="true" lazy="true">    <cache usage="read-write"/>    <key>        <column name="DEPT_ID" />    </key>    <one-to-many class="com.atguigu.hibernate.entities.Employee" /></set>
           II. 注意: 还需要配置集合中的元素对应的持久化类也使用二级缓存! 否则将会多出 n 条 SQL 语句.

3. ehcache 的 配置文件: ehcache.xml

               <!--  指定一个目录:当 EHCache 把数据写到硬盘上时, 将把数据写到这个目录下.-->    

               <diskStore path="d:\\tempDirectory"/>,当SessionFactory关闭的时候,生成的文件会在指定的磁盘上清除。

        <defaultCache
                 maxElementsInMemory="10000"          设置基于内存的缓存中可存放的对象最大数目
                 eternal="false"                                           设置对象是否为永久的, true表示永不过期
                 timeToIdleSeconds="120"                       设置对象空闲最长时间,以秒为单位, 超过这个时间,对象过期
                 timeToLiveSeconds="120"                      设置对象生存最长时间,超过这个时间,对象过期 ,如果此值为0,表示对象可以无限期地存在于缓存中
                 overflowToDisk="true"                              内存的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中
        />

      <cache name="com.atguigu.hibernate.entities.Department.emps"   置缓存的名字,它的取值为类的全限定名或类的集合的名字(集合的缓存策略,类名 . 属性名)
               maxElementsInMemory="1000"
              eternal="true"
              timeToIdleSeconds="0"
              timeToLiveSeconds="0"
              overflowToDisk="false"
        />

       <cache name="com.atguigu.hibernate.entities.Employee"    (类的缓存策略)
             maxElementsInMemory="1"
             eternal="false"
             timeToIdleSeconds="300"
             timeToLiveSeconds="600"
            overflowToDisk="true"
        />



4.  查询缓存: 默认情况下, 设置的缓存对 HQL 及 QBC 查询时无效的, 但可以通过以下方式使其是有效的

                I.  在 hibernate 配置文件中声明开启查询缓存    <property name="cache.use_query_cache">true</property>

               II. 调用 Query 或 Criteria 的 setCacheable(true) 方法

              III. 查询缓存依赖于二级缓存