標籤: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個例子,只需要一個用預設緩衝配置就可以)
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache>
- <diskStore path="java.io.tmpdir"/>
- <defaultCache
- maxElementsInMemory="10000" <!-- 緩衝最大數目 -->
- eternal="false" <!-- 緩衝是否持久 -->
- overflowToDisk="true" <!-- 是否儲存到磁碟,當系統當機時-->
- timeToIdleSeconds="300" <!-- 當緩衝閑置n秒後銷毀 -->
- timeToLiveSeconds="180" <!-- 當緩衝存活n秒後銷毀-->
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds= "120"/>
- </ehcache>
3、在Hibernate設定檔裡面啟用EHCache
說明一下:如果不設定“查詢快取”,那麼hibernate只會緩衝使用load()方法獲得的單個持久化對象,如果想緩衝使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的資料結果集的話, 就需要在設定檔中設定hibernate.cache.use_query_cache true 才行
- <!-- 開啟二級緩衝 -->
- <property name="cache.use_second_level_cache">true</property>
- <!-- 開啟查詢快取 -->
- <property name="hibernate.cache.use_query_cache">true</property>
- <!-- 配置RegionFactory為Ehcache的RegionFactory -->
- <property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
4、配置哪些實體類的對象需要二級緩衝
在Hibernate設定檔hibernate.cfg.xml中統一配置(推薦)
注意,這個<class-cache>標籤必須放在<mapping>標籤的後面!!
[html] view plaincopy
- <!--
- 配置哪些實體類的對象需要二級緩衝
- usage屬性為緩衝策略
- -->
- <class-cache usage="read-only" class="com.ru.domain.Student"/>
說明一下:如果不設定“查詢快取”,那麼hibernate只會緩衝使用load()方法獲得的單個持久化對象,如果想緩衝使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的資料結果集的話, 就需要在設定檔中設定 hibernate.cache.use_query_cache true 才行
- <!-- 開啟查詢快取 -->
- <property name="hibernate.cache.use_query_cache">true</property>