1. 程式人生 > >hibernate 一級和二級快取使用總結

hibernate 一級和二級快取使用總結

   hibernate的快取分為一級快取和二級快取,一級二級和我們常說的cpu的一級二級是不一樣的。這裡的一級說的是session的快取,是hibernate內建的,不能解除安裝。二級說的是SessionFactory中的外接快取,SessionFactory的內建快取是放對映資料和sql語句的,程式不能更改,也不算二級快取。二級快取可以配置和更改,並且動態載入和解除安裝。Hibernate還為查詢結果提供了一個查詢快取,它依賴於第二級快取。 
   二. 一級快取的管理:當應用程式呼叫Session的save()、update()、savaeOrUpdate()、get()或load(),以及呼叫查詢介面的 list()、iterate()或filter()方法時,如果在Session快取中還不存在相應的物件,Hibernate就會把該物件加入到第一級快取中。當清理快取時,Hibernate會根據快取中物件的狀態變化來同步更新資料庫。 Session為應用程式提供了兩個管理快取的方法: evict(Object obj):從快取中清除引數指定的持久化物件。 clear():清空快取中所有持久化物件。 

   三. Hibernate二級快取的管理: 
  1. Hibernate二級快取策略的一般過程如下: 
     1) 條件查詢的時候,總是發出一條select * from table_name where …. (選擇所有欄位)這樣的SQL語句查詢資料庫,一次獲得所有的資料物件。 
     2) 把獲得的所有資料物件根據ID放入到第二級快取中。 
     3) 當Hibernate根據ID訪問資料物件的時候,首先從Session一級快取中查;查不到,如果配置了二級快取,那麼從二級快取中查;查不到,再查詢資料庫,把結果按照ID放入到快取。 
     4) 刪除、更新、增加資料的時候,同時更新快取。Hibernate二級快取策略,是針對於ID查詢的快取策略,對於條件查詢則毫無作用。為此,Hibernate提供了針對條件查詢的Query Cache。 

  2. 什麼樣的資料適合存放到第二級快取中? 
      1) 很少被修改的資料 
      2) 不是很重要的資料,允許出現偶爾併發的資料 
      3) 不會被併發訪問的資料 
      4) 參考資料,指的是供應用參考的常量資料,它的例項數目有限,它的例項會被許多其他類的例項引用,例項極少或者從來不會被修改。 
  3. 不適合存放到第二級快取的資料? 
      1) 經常被修改的資料 
      2) 財務資料,絕對不允許出現併發 
      3) 與其他應用共享的資料。 
  4. 常用的快取外掛 Hibernater二級快取是一個外掛,下面是幾種常用的快取外掛:     
      ◆EhCache:可作為程序範圍的快取,存放資料的物理介質可以是記憶體或硬碟,對Hibernate的查詢快取提供了支援。 

      ◆OSCache:可作為程序範圍的快取,存放資料的物理介質可以是記憶體或硬碟,提供了豐富的快取資料過期策略,對Hibernate的查詢快取提供了支援。 
      ◆SwarmCache:可作為群集範圍內的快取,但不支援Hibernate的查詢快取。    
      ◆JBossCache:可作為群集範圍內的快取,支援事務型併發訪問策略,對Hibernate的查詢快取提供了支援。
      ◆memcached 
     ◆redis 
四、如何配置二級快取 
   4.1如果採用ehcached,配置如下: 
       4.1.1 將相應的二級快取元件jar包匯入到classpath類路徑下 
        4.1.2在hibernate.cfg.xml檔案中配置如下的資訊: 
                  <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> 
                 <property name="hibernate.cache.use_query_cache">true</property> 
                 <property name="cache.use_second_level_cache">true</property> 
                <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
      4.1.3. 指定哪些物件選要被快取:這裡既可以在hibernate.cfg.xml檔案中配置,也可以在對應的hbm檔案中配置 
          4.1.3.1  hibernate.cfg.xml檔案中配置如下:            
                 指定需要快取的物件型別:這裡可以在對映檔案中配置,也可以在hibernate核心配置檔案中進行配置 
                  <class-cache class="com.hib.entity.Inf" usage="read-only" />             
         4.1.3.2  hbm檔案中配置如下: 
                 <cache usage="read-only"/> 在需要快取的元素下新增<cache>元 素,根據需求使用相應的快取級別               
       4.1.4.  在src目錄下編寫一個ehcache.xml檔案,配置一些基本的快取資訊: 
              一般配置資訊如下: 
              <?xml version="1.0" encoding="utf-8"?> 
            <ehcache>      
                <diskStore path="D:/ehcache"/><!--如果快取中的物件儲存超過指定的快取數量的物件儲存的磁碟地址--> 
                <!--全部預設的配置 
                maxElementsInMemory在記憶體中最多存放多少個物件 
                eternal物件是不是永遠不變的,一般都是false 
                timeToLiveSeconds如果這個物件超過了這個時間,就會從快取中清除 
                  --> 
                <defaultCache 
                maxElementsInMemory="500" 
                eternal="false" 
                timeToIdleSeconds="120" 
                timeToLiveSeconds="120" 
                overflowToDisk="true" 
                /> 

                <!-- 針對指定的物件使用的快取配置 
                 name表示的是快取的類物件的全路徑名 --> 
                <cache name="com.hibernate.Student" 
                maxElementsInMemory="500" 
                eternal="false" 
                timeToIdleSeconds="50" 
                timeToLiveSeconds="50" 
                overflowToDisk="true" 
                /> 
            </ehcache> 
    4.1.3.5如果有spring,那麼spring中的配置 
        4.1.3.5.1.在類路徑上ehcache.xml: 

<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="java.io.tmpdir"/> 


     <!--Default Cache configuration. These will applied to caches programmatically created through 
         the CacheManager. 

         The following attributes are required: 

         maxElementsInMemory             - 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. 
         overflowToDisk                  - Sets whether elements can overflow to disk when the in-memory cache 
                                          has reached the maxInMemory limit. 

         The following attributes are optional: 
         timeToIdleSeconds               - Sets the time to idle for an element before it expires. 
                                          i.e. The maximum amount of time between accesses before an element expires 
                                          Is only used if the element is not eternal. 
                                          Optional attribute. A value of 0 means that an Element can idle for infinity. 
                                          The default value is 0. 
         timeToLiveSeconds               - Sets the time to live for an element before it expires. 
                                          i.e. The maximum time between creation time and when an element expires. 
                                          Is only used if the element is not eternal. 
                                          Optional attribute. A value of 0 means that and Element can live for infinity. 
                                          The default value is 0. 
         diskPersistent                  - Whether the disk store persists between restarts of the Virtual Machine. 
                                          The default value is false. 
         diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value 
                                          is 120 seconds. 
         --> 

     <defaultCache 
         maxElementsInMemory="10000" 
         eternal="false" 
         overflowToDisk="true" 
         timeToIdleSeconds="120" 
         timeToLiveSeconds="120" 
         diskPersistent="false" 
         diskExpiryThreadIntervalSeconds="120"/> 

     <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects --> 
</ehcache> 

                   4.1。3.5.2.applicationContext-hibernate.xml裡Hibernate SessionFactory配置: 

     <!-- Hibernate SessionFactory --> 
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
         <property name="dataSource" ref="dataSource"/> 
         <property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property> 
         <!-- The property below is commented out b/c it doesn't work when run via 
              Ant in Eclipse.   It works fine for individual JUnit tests and in IDEA ?? 
         <property name="mappingJarLocations"> 
             <list><value>file:dist/appfuse-dao.jar</value></list> 
         </property> 
         --> 
         <property name="hibernateProperties"> 
             <props> 
                 <prop key="hibernate.dialect">@[email protected]</prop> 
                 <!--<prop key="hibernate.show_sql">true</prop>--> 
                 <prop key="hibernate.max_fetch_depth">3</prop> 
                 <prop key="hibernate.hibernate.use_outer_join">true</prop> 
                 <prop key="hibernate.jdbc.batch_size">10</prop> 
                 <prop key="hibernate.cache.use_query_cache">true</prop> 
                 <prop key="hibernate.cache.use_second_level_cache">true</prop> 
                 <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> 
                 
<!-- 
                 <prop key="hibernate.use_sql_comments">false</prop> 
                 --> 
                 <!-- Create/update the database tables automatically when the JVM starts up 
                 <prop key="hibernate.hbm2ddl.auto">update</prop> --> 
                 <!-- Turn batching off for better error messages under PostgreSQL 
                 <prop key="hibernate.jdbc.batch_size">0</prop> --> 
             </props> 
         </property> 
         <property name="entityInterceptor"> 
            <ref local="auditLogInterceptor"/> 
         </property> 
     </bean> 


啟用class快取: 

    4.2其他快取和spring也是差不多,基本上是導包,自身快取配置,spring配置加上true.    

相關推薦

hibernate 一級二級快取使用總結

   hibernate的快取分為一級快取和二級快取,一級二級和我們常說的cpu的一級二級是不一樣的。這裡的一級說的是session的快取,是hibernate內建的,不能解除安裝。二級說的是SessionFactory中的外接快取,SessionFactory的內建快取是放對映資料和sql語句的,程式不能

hibernate--一級二級快取(使用Ehcache)以及查詢快取

有一下幾點需要理清才行: 一級快取是session快取 session關閉就小時 二級快取是sessionFactory級別的快取 一個應用程式只有一個 多個執行緒共享  不要把經常修改的物件放到二級快取中 二級快取中放一些查詢的物件 1 首先是在hibernate,cfg

Mybatis的一級二級快取

作用域 一級快取:session,當openSession()之後,如果執行相同的sql(相同的語句和引數),Mybatis不執行sql,而是從快取中返回 二級快取:mapper的一個namespace,同一個namespace中查詢sql可以從快取中獲取,二級快取可以跨sessio

一級二級快取使用詳解

【1】一級快取 JPA預設情況下和MyBatis一樣開啟一級快取。JPA是針對與entityManager,Mybatis是針對於namespace。 示例程式碼如下: @Test public void testSecondLevelCache(){ Cust

spring 一級二級快取

最近面試總是被問到spring的一些問題,包括spring的一級和二級快取的問題,那麼究竟什麼事一級快取,什麼是二級快取呢。 一級快取 盜用一下別人的圖,自己是在是懶得畫圖了: 一級快取就是停留在sqlsession級別的,它是用一個hashmap

Hibernate總結--一級快取二級快取

在Hibernate中存在一級快取和二級快取,一級快取時Session 級別的快取,它是屬於事務範圍的快取,這一級別的快取由 hibernate 管理的。一級快取Hibernate預設會實現,當使用get或者load等方式查詢時會將結果存在Session中,在下一次查詢時。若是同一個Session,

mybatishibernate一級二級快取

MyBatis一級快取: hibernate一級快取: 基本差不多  HashMap本地快取,作用域為session,session級別的快取,通過get,update可以將物件放到一級快取中,當 Session flush 或 close&n

Hibernate一級快取二級快取

1:Hibernate的一級快取:   1.1:使用一級快取的目的是為了減少對資料庫的訪問次數,從而提升hibernate的執行效率;(當執行一次查詢操作的時候,執行第二次查詢操作,先檢查快取中是否有資料,如果有資料就不查詢資料庫,直接從快取中獲取資料);    1.

Mybatishibernate一級二級快取問題

Mybatis .一級快取(sqlSession)     一級快取是SqlSession自帶的。SqlSession物件被建立,一級快取就存在了。     如果SqlSession物件關閉或呼叫清理方法,會導致快取失效。     快取底層實現就是通過HashMap實現的。

hibernate快取一級快取二級快取理解

一、什麼是快取:   快取是指為了降低應用程式對物理資料來源訪問的頻次從而提高應用程式的執行效能的一種策略。 二、為什麼使用快取: 1.ORM框架訪問資料庫的效率直接影響應用程式的執行速度,提升和優化ORM框架的執行效率至關重要。 2.Hibernate的快取是提升和

hibernate一級快取二級快取的區別

                       快取是介於應用程式和物理資料來源之間,其作用是為了降低應用程式對物理資料來源訪問的頻次,從而提高了應用的執行效能。快取內的資料是對物理資料來源中的資料的複製,應用程式在執行時從快取讀寫資料,在特定的時刻或事件會同步快取和物理資料來源的資料。   快取的介質一般是記

客觀面試題--30.hibernate一級快取二級快取有什麼區別?

快取是介於應用程式和物理資料來源之間,其作用是為了降低應用程式對物理資料來源訪問的頻次,從而提高了應用的執行效能。快取內的資料是對物理資料來源中的資料的複製,應用程式在執行時從快取讀寫資料,在特定的時刻或事件會同步快取和物理資料來源的資料。  快取的介質一般是記憶體,所以讀寫

java Hibernate一級快取二級快取概念案例詳解

  一、一級快取二級快取的概念解釋   (1)一級快取就是Session級別的快取,一個Session做了一個查詢操作,它會把這個操作的結果放在一級快取中,如果短時間內這個   session(一定要同一個session)又做了同一個操作,那麼hibernate直接從一級快

hibernate一級快取二級快取的區別與聯絡

快取是介於應用程式和物理資料來源之間,其作用是為了降低應用程式對物理資料來源訪問的頻次,從而提高了應用的執行效能。快取內的資料是對物理資料來源中的資料的複製,應用程式在執行時從快取讀寫資料,在特定的時刻或事件會同步快取和物理資料來源的資料。   快取的介質一般是記憶體,

Hibernate快取一級快取二級快取

1.什麼是快取?  快取是介於物理資料來源與應用程式之間,是對資料庫中的資料複製一份臨時放在記憶體中的容器,其作用是為了減少應用程式對物理資料來源訪問的次數,從而提高了應用程式的執行效能。Hibernate在進行讀取資料的時候,根據快取機制在相應的快取中查詢,如果在快取中找到了需要的資料(我們把這稱做“快取

hibernate一級快取二級快取機制

Hibernate是一個持久層框架,經常訪問物理資料庫,為了降低應用程式對物理資料來源訪問的頻次,從而提高應用程式的執行效能,hibernate出現了快取機制,總的來說,快取機制是為了減少對資料訪問資料庫的頻率,應用程式從記憶體中讀取持久化物件的速度顯然比到資

hibernate中的一級快取二級快取

package test; import org.hibernate.Session; import com.wxh.dto.People; import com.wxh.sessionfactory.HibernateSessionFactory; public cl

Hibernate一級快取二級快取詳解

一、一級快取二級快取的概念解釋 (1)一級快取就是Session級別的快取,一個Session做了一個查詢操作,它會把這個操作的結果放在一級快取中,如果短時間內這個 session(一定要同一個se

hibernate一級快取二級快取的具體區別

一、Session快取(又稱作事務快取):Hibernate內建的,不能卸除。 快取範圍:快取只能被當前Session物件訪問。快取的生命週期依賴於Session的生命週期,當Session被關閉後,快取也就結束生命週期。 Hibernate一些與一級快取相關的操作(時間點): 資料放入快取: 1. save

Hibernate一級快取Session二級快取SessionFactory

Hibernate的一級快取是指Session(屬於事務範圍的快取,由Hibernate管理,無需干預),它是一塊記憶體空間,用來存放相互管理的java物件,有了一級快取,應用程式可以減少訪問資料庫的次數,提高了效能。 在使用Hibernate查詢物件的時候,