十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
(一)Hibernate的二級緩存策略的一般過程如下:
1) 條件查詢的時候,總是發(fā)出一條select * from table_name where …. (選擇所有字段)這樣的SQL語句查詢數(shù)據(jù)庫,一次獲得所有的數(shù)據(jù)對象。

2) 把獲得的所有數(shù)據(jù)對象根據(jù)ID放入到第二級緩存中。
3) 當Hibernate根據(jù)ID訪問數(shù)據(jù)對象的時候,首先從Session一級緩存中查;查不到,如果配置了二級緩存,那么從二級緩存中查;查不到,再查詢數(shù)據(jù)庫,把結(jié)果按照ID放入到緩存。
4) 刪除、更新、增加數(shù)據(jù)的時候,同時更新緩存。
Hibernate的二級緩存策略,是針對于ID查詢的緩存策略,對于條件查詢則毫無作用。為此,Hibernate提供了針對條件查詢的Query Cache。
(二)什么樣的數(shù)據(jù)適合存放到第二級緩存中?
1 很少被修改的數(shù)據(jù)
2 不是很重要的數(shù)據(jù),允許出現(xiàn)偶爾并發(fā)的數(shù)據(jù)
3 不會被并發(fā)訪問的數(shù)據(jù)
4 參考數(shù)據(jù),指的是供應(yīng)用參考的常量數(shù)據(jù),它的實例數(shù)目有限,它的實例會被許多其他類的實例引用,實例極少或者從來不會被修改。
(三)不適合存放到第二級緩存的數(shù)據(jù)?
1 經(jīng)常被修改的數(shù)據(jù)
2 財務(wù)數(shù)據(jù),絕對不允許出現(xiàn)并發(fā)
3 與其他應(yīng)用共享的數(shù)據(jù)。
實踐部分:
使用EhCache配置二級緩存:
配置準備:
1)把ehcache-1.2.3.jar加入到當前應(yīng)用的classpath中。
2)在hibernate.cfg.xml文件中加入EhCache緩存插件的提供類。
- org.hibernate.cache.EhCacheProvider
3)挎貝ehcache.xml文件到類路徑(項目工程的src目錄下),這個文件在Hibernate安裝目錄的etc下。
配置步驟:
Hibernate允許在類和集合的粒度上設(shè)置第二級緩存。在映射文件中,
示例:以category(產(chǎn)品類別)和product(產(chǎn)品)的映射為例:
1) 修改要配置緩存的那個持久化類的對象關(guān)系映射文件:
Category.hbm.xml
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- 配置緩存,必須緊跟在class元素后面
- 對緩存中的Category對象采用讀寫型的并發(fā)訪問策略
- -->
Product.hbm.xml
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- column="categoryId"
- class="org.qiujy.domain.cachedemo.Category"
- cascade="save-update"
- not-null="true">
2)編輯ehcache.xml文件:
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- />
- maxElementsInMemory="100"
- eternal="true"
- timeToIdleSeconds="0"
- timeToLiveSeconds="0"
- overflowToDisk="false"
- />
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="300"
- timeToLiveSeconds="600"
- overflowToDisk="true"
- />
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="300"
- timeToLiveSeconds="600"
- overflowToDisk="true"
- />
在Spring托管的Hibernate中使用二級緩存 1.在spring的配置文件中,hibernate部分加入 xml 代碼 org.hibernate.cache.EhCacheProvider true 2.為HBM表設(shè)置cache策略 xml 代碼 3.在DAO中,調(diào)用find方法查詢之前,設(shè)置使用緩存 Java代碼 getHibernateTemplate().setCacheQueries(true); 補充: 如果不設(shè)置“查詢緩存”,那么hibernate只會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的數(shù)據(jù)結(jié)果集的話,就需要設(shè)置 hibernate.cache.use_query_cache true 才行。
【編輯推薦】