Hibernate 二級緩存

最近要做一個小東西,自己學着用一下hibernate 的二級緩存,雖然說就是幾個配置的問題,不過搞得不好,配置中會發生很多問題。

 以在我們用hibernate3.2中,我們配置二級緩存如下:

<property name="cache.use_second_level_cache">true</property> 

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

<property name="hibernate.cache.use_query_cache">true</property>

另外在jar中,我們用的是\lib\optional\ehcache\ehcache1.23.jar

但是今天我在做測試的時候,用得是hibernate-core-4.1.2-final版本,做了半天也沒有成功,最後在網上不斷的找資料,最終找到錯誤原因:

在hibernate4中,配置cache與hibernate3.2是不一樣的

<session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
  <property name="connection.username">root</property>
  <property name="connection.password">901206</property>
  <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
  <property name="cache.use_second_level_cache">true</property>  
  <property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
  <property name="hibernate.cache.use_query_cache">true</property>
  <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
  <property name="show_sql">true</property>
  <property name="use_sql_comments">true</property>
  <property name="hbm2ddl.auto">update</property>
  <mapping class="com.Stu001"/>
 </session-factory>

其中:

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

改爲:

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>

<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
這個屬性可以不寫,hibernate會默認的到classess 中找到ehcache.xml,如果你自己不是用默認的名ehcache.xml,那麼你就必須得寫這了屬性。

哎,搞半天可以了,希望能爲後面的學習人少走彎路,提供一個借鑑。

ehcache.xml配置如下:

 <diskStore path="d:/temp"/>,配置這個之後

在d:/temp中會增加三個文件

com.Stu001.data

org.hibernate.cache.internal.StandardQueryCache.data

org.hibernate.cache.spi.UpdateTimestampsCache.data

發佈了14 篇原創文章 · 獲贊 17 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章