從hibernate2.1開始ehcache已經作為hibernate的默認緩存方案(二級緩存方案 sessionfactory級別), 在項目中有針對性的使用緩存將對性能的提升右很大的幫助。
要使用 Ehcache:需要一下步驟
一,classpath添加相應的jar(ehcache,commons-logging)
二,然后在hibernate.cfg.xml中配置
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
說明:如果沒有配置<property name="cache.use_second_level_cache">true</property>(默認false) 將會產生根據單個id查詢的情況(產生很多sql)。
三,為需要緩存的類添加緩存標示:
使用mapping文件時需要添加node :
Java代碼
@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
如果使用使用hibernate annoation是使用@Cache(usage=CacheConcurrencyStrategy.)標簽,有5種可選的緩存方案:
1,CacheConcurrencyStrategy.NONE
不適用,默認
2. CacheConcurrencyStrategy.NONSTRICT_READ_WRITE
更新不頻繁幾個小時或更長
3,CacheConcurrencyStrategy.READ_ONLY
對於不發生改變的數據使用 [size=large][/size]
4,CacheConcurrencyStrategy.READ_WRITE
基於時間戳判定機制,,對於數據同步要求嚴格的情況,使用頻繁
5,CacheConcurrencyStrategy.TRANSACTIONAL
運行在jta環境種,基於事務
