Hibernate4.1.4配置二級緩衝EHCache步驟

來源:互聯網
上載者:User

標籤:blog   http   java   使用   strong   檔案   

1、當然首先引入EHCache相關的jar包

 

這些包不需要另外下載,在Hibernate官方網站下載Hibernate4.1.7的壓縮包(如:hibernate-release-4.1.7.Final.zip)解壓,引入hibernate-release-4.1.7.Final\hibernate-release-4.1.7.Final\lib\optional\ehcache目錄下的ehcache-core-2.4.3.jar、hibernate-ehcache-4.1.4.Final.jar、slf4j-api-1.6.1.jar三個jar包即可(就是添加到referenced libraries下)。

 

2、在項目classpath的根目錄下面寫好EHCache的設定檔ehcache.xml

 

此設定檔可以直接到HIBERNATE_HOME\project\etc\ehcache.xml拷貝到src目錄下即可。(裡面有3個例子,只需要一個用預設緩衝配置就可以)

  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <ehcache>   
  3.  <diskStore path="java.io.tmpdir"/>   
  4.   <defaultCache   
  5.    maxElementsInMemory="10000" <!-- 緩衝最大數目 -->   
  6.    eternal="false" <!-- 緩衝是否持久 -->   
  7.    overflowToDisk="true" <!-- 是否儲存到磁碟,當系統當機時-->   
  8.    timeToIdleSeconds="300" <!-- 當緩衝閑置n秒後銷毀 -->   
  9.    timeToLiveSeconds="180" <!-- 當緩衝存活n秒後銷毀-->   
  10.    diskPersistent="false"   
  11.    diskExpiryThreadIntervalSeconds= "120"/>   
  12. </ehcache>   

3、在Hibernate設定檔裡面啟用EHCache

 

說明一下:如果不設定“查詢快取”,那麼hibernate只會緩衝使用load()方法獲得的單個持久化對象,如果想緩衝使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的資料結果集的話, 就需要在設定檔中設定hibernate.cache.use_query_cache true 才行

  1. <!-- 開啟二級緩衝 -->  
  2. <property name="cache.use_second_level_cache">true</property>  
  3.  <!-- 開啟查詢快取 -->    
  4. <property name="hibernate.cache.use_query_cache">true</property>                   
  5. <!-- 配置RegionFactory為Ehcache的RegionFactory -->  
  6. <property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>  


4、配置哪些實體類的對象需要二級緩衝

在Hibernate設定檔hibernate.cfg.xml中統一配置(推薦)

 

  注意,這個<class-cache>標籤必須放在<mapping>標籤的後面!!

[html] view plaincopy 
  1. <!--   
  2.         配置哪些實體類的對象需要二級緩衝  
  3.         usage屬性為緩衝策略  
  4. -->  
  5. <class-cache usage="read-only" class="com.ru.domain.Student"/>  


 

說明一下:如果不設定“查詢快取”,那麼hibernate只會緩衝使用load()方法獲得的單個持久化對象,如果想緩衝使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的資料結果集的話, 就需要在設定檔中設定 hibernate.cache.use_query_cache true 才行 

 

    1. <!-- 開啟查詢快取 -->    
    2. <property name="hibernate.cache.use_query_cache">true</property>    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.