Hibernate二級緩存 的配置詳解(ssh)

jopen 12年前發布 | 48K 次閱讀 Hibernate 持久層框架

1、首先設置EhCache,導入ehcache.jar,建立配置文件ehcache.xml,默認的位置在class-path,可以放到你的src目錄下:

<?xml version="1.0" encoding="UTF-8"?>
 <ehcache>
  <diskStore path="java.io.tmpdir"/>
   <defaultCache
    maxElementsInMemory="10000" <!-- 緩存最大數目 -->
    eternal="false" <!-- 緩存是否持久 -->
    overflowToDisk="true" <!-- 是否保存到磁盤,當系統當機時-->
    timeToIdleSeconds="300" <!-- 當緩存閑置n秒后銷毀 -->
    timeToLiveSeconds="180" <!-- 當緩存存活n秒后銷毀-->
    diskPersistent="false"
    diskExpiryThreadIntervalSeconds= "120"/>
 </ehcache>

  2、在Hibernate配置文件中設置:

<!--打開二級緩存-->

<prop key="hibernate.cache.use_second_level_cache">true</prop>

<!-- 設置Hibernate的緩存接口類,這個類在Hibernate包中 -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
  <!-- 是否使用查詢緩存 -->
  <property name="hibernate.cache.use_query_cache">true</property>
   如果使用spring調用Hibernate的sessionFactory的話,這樣設置:
   <!--HibernateSession工廠管理 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
     <ref bean="datasource" />
    </property>
    <property name="hibernateProperties">
    <props>
     <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
     <prop key="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
     <prop key="hibernate.show_sql">true</prop>
     <prop key="hibernate.cache.use_query_cache">true</prop>
     <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
    </props>
  </property>
  <property name="mappingDirectoryLocations">
   <list>
    <value>/WEB-INF/classes/cn/rmic/manager/hibernate/</value>
   </list>
  </property>
 </bean>

   說明一下:如果不設置“查詢緩存”,那么hibernate只會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的數據結果集的話,就需要設置hibernate.cache.use_query_cache true 才行

  3、在Hbm文件中添加<cache usage="read-only"/>

   4、如果需要“查詢緩存”,還需要在使用Query或Criteria()時設置其setCacheable(true);屬性

  

public List selectHql(String hql) {

getHibernateTemplate().setCacheQueries(true);

return getHibernateTemplate().find(hql);

}

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!