hiernate二级缓存区域

区域即是一个具有名称的高速缓存块,你可以给每一个高速缓存块设置不同的缓存策略。如果没有设置任何的缓存区域,

则所有被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>

     对于类而言,区域的名称是类名。如:cn.itcast.domain.Person(一般情况后面会跟一个.data)

     对于集合而言,区域的名称是类名加属性名。如cn.itcast.domain.Person.cars(一般情况,后面会跟一个.data)

  hibernate的配置属性:hibernate.cache.region_prefix可以给每一个区域配置一个前缀的名称。但这种情况一般发生在一个项目中

 有多个SessionFactory的情况。如果一个项目有多个SessionFactory则此配置也是必须的。

    以下是示例:ehcache的具名缓存区域配置示例:

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:noNamespaceSchemaLocation="ehcache.xsd"

         updateCheck="true" monitoring="autodetect"

         dynamicConfig="true">

    <diskStore path="d:/a"/>     //指定文件保存路径

    <defaultCache     //配置默认缓存区域,这是必须配置项。如果没有给某个类设置缓存区域,它将使用默认缓存区域

        maxElementsInMemory="100"

        eternal="false"

        timeToIdleSeconds="120"

        timeToLiveSeconds="300"

        overflowToDisk="true"

        />

    <cache name="cn.itcast.domain.Person"  //指定Person类的缓存区域,所有Person类,都会保存在此区域

       maxElementsInMemory="2"           //故意指定内存中放很少的数据,以观察生成的文件大小

        eternal="false"

        timeToIdleSeconds="120"

        timeToLiveSeconds="300"

        overflowToDisk="true"

        diskPersistent="true"

        diskExpiryThreadIntervalSeconds="120"

        maxElementsOnDisk="100"

        >

    </cache>

</ehcache>

   测试代码:一次生成多个Person实例,看看生成的文件大小:

        Session s1 = HibernateUtils.openSession();   

       Person p1 = (Person) s1.get(Person.class,"11");

       Person p2 = (Person) s1.get(Person.class,"402880e 6346f 5ffe 01346f 6000b50000");

       Person p3 = (Person) s1.get(Person.class,"402880e6347311fa01347311fb 7c 0000");

       s1.close();
<!--[if !supportLineBreakNewLine]-->

1、理解高速查询缓存区域

     当某个查询第一次执行时,它的结果被高速缓存在高速缓存区域--注意,这个区域不同于你可能已经配置的任何其他实例或

     集合高速缓存区域。这个区域的名称默认为:org.hibernate.cache.StandardQueryCache。

     可以通过setCacheRegion(...)方法,给一个特定的查询改变高速缓存区域。

         hql = "from Person where name='JackB'";

       list = s.createQuery(hql)

              .setCacheable(true)

              .setCacheRegion("itcast")  //改变默认缓存查询区域

              .list();

    或是显示的设置一个查询缓存区域,以观察它的保存情况:

     <cache name="org.hibernate.cache.StandardQueryCache"   //必须叫这个名称

       maxElementsInMemory="2"

        eternal="false"

        timeToIdleSeconds="120"

        timeToLiveSeconds="300"

        overflowToDisk="true"

        diskPersistent="true"

        diskExpiryThreadIntervalSeconds="120"

        maxElementsOnDisk="100"

        />

2、时间戳高速缓存区域

     如果查询结果高速缓存被启用,另一个始终需要的高速缓存区域也出现了:org.hibernate.cache.UpdateTimestampsCache。

      这是Hibernate内部使用的一个高速缓存区域。Hibernate用时间戳来决定被高速缓存的结果集是否已经失效。

 

使用二级缓存的项目建议

    并非所有的类都可以受益于高速二级缓存,因为,能够禁用高速二级缓存也很重要。重申一下,高速缓存通常只对于主要用来读取的

类有用。如果你有更新比读取更经常的数据,就不要启用二级高速缓存,即使所有其他的高速缓存条件都符合!

更新期间,维护高速缓存的代价可能远远超出更快读取的性能受益。

posted on 2014-05-20 00:46  艾佳龙  阅读(439)  评论(0编辑  收藏  举报