Hibernate4 二級快取配置
阿新 • • 發佈:2019-01-23
1、Hibernate配置檔案開啟二級快取
3、在對映檔案 *.hbm.xml 中設定快取策略
【提示】二級快取的策略一般有:read-only、nonstrict-read-write、read-write、transactional。
通常二級快取都配置成read-only,否則如果對快取進行讀寫,效能會變差,快取就失去了意義。
4、驗證Hibernate是否從二級快取中獲取資料
【提示】如果我們只是取出物件的一些屬性的話,則不會將其儲存到二級快取中去,因為二級快取快取的僅僅是物件。
【提示】在Log4j中加上以下程式碼可以看到Hibernate從快取中查詢資料,注意,以下配置需要使用slf4j的JAR包
log4j.logger.org.hibernate=debug
<!--開啟二級快取--> <property name="hibernate.cache.use_second_level_cache">true</property> <!--指定二級快取的提供類--> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!--指定二級快取配置檔案的位置--> <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>
【注意】
這裡使用的是hibernate4.xx版本,如果是hibernate3.xx版本,則二級快取提供類改為如下配置:
<!--這個類在4.0以後不建議使用-->
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
2、配置EHCache快取,建立ehcache.xml檔案,放到專案根目錄下,ehcache.xml內容如下
<ehcache updateCheck="false"> <!-- 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" /> <!--<diskStore path="user.dir" />--> <!--可以每個實體類指定一個對應的快取,如果沒有匹配到該類,則使用這個預設的快取配置--> <!-- maxElementsInMemory: 在記憶體中存放的最大物件數; eternal: 是否永久儲存快取,設定成false; timeToLiveSeconds: 以建立時間為基準開始計算的超時時長; timeToIdleSeconds: 在建立時間和最近訪問時間中取出離現在最近的時間作為基準計算的超時時長; overflowToDisk: 如果物件數量超過記憶體中最大的數,是否將其儲存到磁碟中,設定成true; 如果僅設定timeToLiveSeconds,則該物件的超時時間=建立時間+timeToLiveSeconds,假設為A; 如果沒設定timeToLiveSeconds,則該物件的超時時間=max(建立時間,最近訪問時間)+timeToIdleSeconds,假設為B; 如果兩者都設定,則取出A、B中的較小值,即min(A,B),表示只要有一個超時成立即算超時; --> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <!--可以給每個實體類指定一個配置檔案,通過name屬性指定,要使用類的全名--> <!--<cache name="com.xiaoluo.bean.Student" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />--> </ehcache>
3、在對映檔案 *.hbm.xml 中設定快取策略
class 節點新增如下配置
<!--快取策略-->
<cache usage="read-only" />
【提示】二級快取的策略一般有:read-only、nonstrict-read-write、read-write、transactional。
通常二級快取都配置成read-only,否則如果對快取進行讀寫,效能會變差,快取就失去了意義。
4、驗證Hibernate是否從二級快取中獲取資料
【提示】如果我們只是取出物件的一些屬性的話,則不會將其儲存到二級快取中去,因為二級快取快取的僅僅是物件。
【提示】在Log4j中加上以下程式碼可以看到Hibernate從快取中查詢資料,注意,以下配置需要使用slf4j的JAR包
log4j.logger.org.hibernate=debug
轉載: http://www.360doc.com/content/14/0801/16/1073512_398635409.shtml
轉載: http://www.cnblogs.com/xiaoluo501395377/p/3377604.html
參考: http://my.oschina.net/alexgaoyh/blog/348188