1. 在Hibernate配置文件中設(shè)置:
如果不設(shè)置“查詢緩存”,那么hibernate只會(huì)緩存使用load()方法獲得的單個(gè)持久化對(duì)象,如果想緩存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法獲得的數(shù)據(jù)結(jié)果集的話,就需要設(shè)置hibernate.cache.use_query_cache true 才行 2.首先設(shè)置EhCache,建立配置文件ehcache.xml,默認(rèn)的位置在class-path,可以放到你的src目錄下:
以com.ouou.model.Videos為例子 在Videos.hbm.xml中配置: <class name="Videos" table="TEST" lazy="false"> <cache usage="read-write" region="ehcache.xml中的name的屬性值"/>注意:這一句需要緊跟在class標(biāo)簽下面,其他位置無效。 hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的屬性值",則使用name名為com.ouou.model.Videos的cache, 如果不存在與類名匹配的cache名稱,則用defaultCache。 如果Videos包含set集合,則需要另行指定其cache 例如Videos包含Tags集合,則需要 添加如下配置到ehcache.xml中 <cache name="com.ouou.model.Tags" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" /> 另,針對(duì)查詢緩存的配置如下: <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="true" overflowToDisk="true"/> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" eternal="false" timeToLiveSeconds="120" overflowToDisk="true"/> 3、 選擇緩存策略依據(jù): <cache usage="transactional|read-write|nonstrict-read-write|read-only" (1)/> ehcache不支持transactional,其他三種可以支持。 read-only:無需修改, 那么就可以對(duì)其進(jìn)行只讀 緩存,注意,在此策略下,如果直接修改數(shù)據(jù)庫,即使能夠看到前臺(tái)顯示效果, 但是將對(duì)象修改至cache中會(huì)報(bào)error,cache不會(huì)發(fā)生作用。另:刪除記錄會(huì)報(bào)錯(cuò),因?yàn)椴荒茉趓ead-only模式的對(duì)象從cache中刪除。 read-write:需要更新數(shù)據(jù),那么使用讀/寫緩存 比較合適,前提:數(shù)據(jù)庫不可以為serializable transaction isolation level (序列化事務(wù)隔離級(jí)別) nonstrict-read-write:只偶爾需要更新數(shù)據(jù)(也就是說,兩個(gè)事務(wù)同時(shí)更新同一記錄的情況很不常見),也不需要十分嚴(yán)格的事務(wù)隔離, 那么比較適合使用非嚴(yán)格讀/寫緩存策略。 4、 調(diào)試時(shí)候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作過程,主要用于調(diào)試過程,實(shí)際應(yīng)用發(fā)布時(shí)候,請(qǐng)注釋掉,以免影響性能。 5、 使用ehcache,打印sql語句是正常的,因?yàn)閝uery cache設(shè)置為true將會(huì)創(chuàng)建兩個(gè)緩存區(qū)域:一個(gè)用于保存查詢結(jié)果集 ( org.hibernate.cache.StandardQueryCache);另一個(gè)則用于保存最近查詢的一系列表的時(shí)間戳(org.hibernate.cache.UpdateTimestampsCache)。 請(qǐng)注意:在查詢緩存中,它并不緩存結(jié)果集中所包含的實(shí)體的確切狀態(tài);它只緩存這些實(shí)體的標(biāo)識(shí)符屬性的值、以及各值類型的結(jié)果。 需要將打印sql語句與最近的cache內(nèi)容相比較,將不同之處修改到cache中,所以查詢緩存通常會(huì)和二級(jí)緩存一起使用。 英文參考資料:http://ehcache.sourceforge.net/documentation/#mozTocId258426 博文參考:http://blog.csdn.net/yun15291li/archive/2006/02/21/604095.aspx http://zyl.javaeye.com/blog/68369 其他:http://dev.yesky.com/157/2557157.shtml