关于hibernate的cache总结及并发问题

缓存按应用范围可分为三类:

事物级缓存即一级缓存session缓存:

         存储的当前session相关联java对象

                  session缓存称为hibernate的一级缓存

         应用级缓存即二级缓存sessionFactory:

                   二级缓存根据目的和功能又可分为内置缓存和外置缓存。

                   内置缓存放置的是映射元数据和预定义SQL语句,内置缓存是只读的,不可修改。

                   外置缓存是一个可配置的插件,在默认情况hibernate不会开启这个插件。

                   外置缓存的存储介质是内存或硬盘。

                   SessionFactory的外置缓存被称为hibernate的二级缓存。

      hibernate本身只提供二级缓存的规范,有第三方插件做具体实现。EHCache。

      二级缓存存储的对象分为:

        类对象

        集合对象

        query查询对象

        集群范围缓存

EHCache缓存在hibernate中的使用;

   1.在主配置文件中要开启二级缓存:

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

   2.在主配置文件配置二级缓存区工厂:

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

   3.指定缓存对象(可在映射关系中配置也可在主配置文件中配置)

         0.导入Jar包和配置文件

          

         1.<class-cache usage="read-only" class="指定的对象类"/>(主配置文件中配置)

         2. <collection-cache usage="read-only" collection="指定的集合对象"/>(主配置文件中配置)

<!-- 指定类缓存集合 -->
<class-cache usage="read-only" class="com.layne.beans.Minister"/>
<class-cache usage="read-only" class="com.layne.beans.Country"/>
<!-- 指定集合缓存集合 -->
<collection-cache usage="read-only" collection="com.layne.beans.Country.ministers"/>

在映射关系配置文件中配置

 <class name="Country">
           <!-- 指定当前类为类缓存对象 -->
           <!-- <cache usage="read-only"/> -->
           <id name="cid">
              <generator class="native"></generator>
           </id>
           <property name="cname"/>
           <!-- 对关系关联映射关系 -->
           <set name="ministers" cascade="save-update" inverse="false">
              <!-- 指定当前集合为缓存对象 -->
             <!--  <cache usage="read-only"/> -->
              <key column="countryId"/>
              <one-to-many class="Minister"/>
           </set>
     </class>

       3.配置query查询缓存对象

        在主配置文件中开启query缓存:<property name="hibernate.cache.use_query_cache">true</property>

           query查询的结果也是可以存到一二级缓存中,但Query查询默认不会从缓存中读取数据     

            要使用Query读取缓存数据
           1.在Hibernate.cfg.xml配置hibernate.cache.use_query_cache为true
           2.要在Query语句添加 setCacheable(true):

                     Country country= (Country) session.createQuery(hql).setCacheable(true).uniqueResult();

Session的刷新与同步

     Session的刷新是指,Session缓存中数据的更新。

    Session的同步是指,将Session缓存中的数据同步更行到DB中。

    执行同步的时间点只有一个:事物的提交。

    刷新的时间点有三个:1.执行Query查询 2.执行Session.flush() 3.执行事物的提交

    当代码中执行了对Session中现有数据的修改操作,即update()与delete()语句后,

            Session缓存并不会马上刷新。即并不会马上执行update与delete的SQL语句。

原文地址:https://www.cnblogs.com/flytogalaxy/p/7473582.html