初識Hibernate 緩衝,初識hibernate緩衝

來源:互聯網
上載者:User

初識Hibernate 緩衝,初識hibernate緩衝

    生活就像一杯咖啡,讓你我慢慢的品嘗,品嘗它的苦澀和甘甜......

一、什麼是Hibernate緩衝。

   解析:白話來說就是快取資料的容器

      官方標準點緩衝:是電腦領域的概念,它介於應用程式和永久性資料存放區源之間。

      作用:降低應用程式直接讀寫資料庫的頻率,從而提高程式的運行效能。緩衝中的資料是資料存放區源中資料的拷貝。緩衝的物理介質通常是記憶體。

二、緩衝一般分為三個類

  一級緩衝

  二級緩衝

  查看緩衝

三、一級緩衝

情境一:使用同一個session連續查詢兩次同一個對象

/查詢學生資訊    public static void select(){                //由班級查詢該班級學生資訊        Session session=HibernateUtil.currentSession();        Grade grade=(Grade) session.get(Grade.class, 14);        //輸出班級資訊        System.out.println(grade.getGname());        Grade grade2=(Grade) session.get(Grade.class, 14);        //輸出班級資訊        System.out.println(grade2.getGname());    }

執行結果:

情境一:在第一次查詢完畢後,關閉session對象,重新開啟一個session然後繼續查詢同一個對象

//查詢學生資訊    public static void select(){                //由班級查詢該班級學生資訊        Session session=HibernateUtil.currentSession();        Grade grade=(Grade) session.get(Grade.class, 14);        //輸出班級資訊        System.out.println(grade.getGname());        //關閉session        HibernateUtil.closeSession();        //重新擷取session        session=HibernateUtil.currentSession();        Grade grade2=(Grade) session.get(Grade.class, 14);        //輸出班級資訊        System.out.println(grade2.getGname());    }

執行結果:

 

解析:

   1:當我沒有關閉session時用的同一個session兩次訪問同一個對象時,只會向DB端發送一條sql語句
    * 原因:因為我第一次訪問資料庫的時候Hibernate會自動的將我查詢出來的結果保留一份查詢出來的對象到一級緩衝
          並且這個額對象是根據OID唯一標識的,也可以理解為資料庫中的主索引值,然後當我再一次訪問一個對象時,Hibernate
        機制會自動的先去一級緩衝中尋找看有沒有OID與我要查詢的OID相同的對象,如果有的話,則直接從一級緩衝中 拿資料
          如果沒有相同的OID則說明緩衝中沒有我要的記錄,那麼就會直接去訪問DB端了,這樣的話,又會重新發送一條sql
    2:當我第一次查詢完資料後立即關閉session,這時重新開啟一個session來訪問同一個對象,這時我們會發現它居然向資料庫發送了兩條Sql語句。這是為什麼呢?
    * 原因:其實原因很簡單,因為我們雖然說是訪問的同一個對象,但是我們隨即就關閉了這個session而重新開啟了一個session,

        此時我們訪問時的session是不一致的也就是說是兩個不同的session發出的請求,這樣理解的話,我們就不難理解了。

          所以總結出,一級緩衝是一個會話層級的緩衝,當一次回話結束後該會話裡的緩衝則會全部的銷毀,所有我們自然就只能重新發送一條sql啦。

3補充以下方法支援一級緩衝

 

 

 四、二級緩衝

(一)配置二級緩衝 

  1.引入如下jar包。

        ehcache-1.2.3.jar  核心庫

        backport-util-concurrent.jar

        commons-logging.jar

  2.配置Hibernate.cfg.xml開啟二級緩衝

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

 

 

 

     3.配置二級緩衝的供應商

        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

 

 

 

  4.指定使用二級緩衝的類

    方案一:在*.hbm.xml中配置

         在<class元素的子項目下添加chche子節點,但該配置僅會緩衝對象的簡單屬性,若希望緩衝集合屬性中的元素,必須在set元素中添加<cache>子項目

          <class name="Student" table="STUDENT">

        <cache usage="read-write"/>

 

 

 

    方案二:在大設定檔(hibernate.cfg.xml)中配置

         <class-cache usage="read-write" class="cn.happy.entity.Student"/>

          <collection-cache usage="read-write" collection=""/>--可注釋如果配置不成功

 

 

 

    注意大配置的書寫位置

      Multiple annotations found at this line:

         - The content of element type "session-factory" must match "(property*,mapping*,(class-cache|collection-

          cache)*,event*,listener*)".

         - Start tag of element <session-factory>

 

    *5.在src下添加ehcache.xml檔案,從etc擷取檔案即可。

      

<ehcache>    <!-- Sets the path to the directory where cache .data files are created.         If the path is a Java System Property it is replaced by         its value in the running VM.         The following properties are translated:         user.home - User's home directory         user.dir - User's current working directory         java.io.tmpdir - Default temp file path -->    <diskStore path="d:/tmp"/>    <!--Default Cache configuration. These will applied to caches programmatically created through        the CacheManager.        The following attributes are required for defaultCache:        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        />    <!--Predefined caches.  Add your cache configuration settings here.        If you do not have a configuration for your cache a WARNING will be issued when the        CacheManager starts        The following attributes are required for defaultCache:        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <!-- Sample cache named sampleCache1        This cache contains a maximum in memory of 10000 elements, and will expire        an element if it is idle for more than 5 minutes and lives for more than        10 minutes.        If there are more than 10000 elements it will overflow to the        disk cache, which in this configuration will go to wherever java.io.tmp is        defined on your system. On a standard Linux system this will be /tmp"        -->    <cache name="sampleCache1"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"        />    <!-- Sample cache named sampleCache2        This cache contains 1000 elements. Elements will always be held in memory.        They are not expired. -->    <cache name="sampleCache2"        maxElementsInMemory="1000"        eternal="true"        timeToIdleSeconds="0"        timeToLiveSeconds="0"        overflowToDisk="false"        /> -->    <!-- Place configuration for your caches following --></ehcache>

 

(二二級緩衝散裝資料原理圖 

解析:每次從二級緩衝中取出的對象,都是一個新的對象。

(三)什麼樣的資料適合放入二級緩衝中?

  1很少被修改的資料

  2不是很重要的資料,允許出現偶爾並發的資料

  3不會被並發訪問的資料

  4參考資料,指的是供應用參考的常量資料,它的實列數目有限,它的實列被許多其他類的實列引用,實列極少或者從來不會被修改。

 

 

講述幾乎結束了!!!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.