歡迎您光臨本站 註冊首頁

hibernate的二級緩存介紹

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

  hibernate二級緩存是由SessionFactory管理,所以又叫SessionFactory級緩存,它是通過不同的類庫來實現的,比如ehcache、oscache等.和一級緩存一樣,二級緩存也是用來緩存實體對象的,對普通屬性不緩存.

  hibernate二級緩存的使用需要進行必要的配置,主要是四個地方(這裡以ehcache為例):

  1>. 配置echcache.xml文件

  2>.開啟二級緩存,修改hibernate.cfg.xml文件

  true

  3>.指定緩存產品提供商,修改hibernate.cfg.xml文件

  org.hibernate.cache.EhCacheProvider

  4>.指定那些實體類使用二級緩存(兩種方法)

  1).在映射文件中採用標籤

  2).在hibernate.cfg.xml文件中,採用標籤

  hibernate二級緩存配置上之後,就成了「客觀存在」,hibernate在使用某些方法的時候默認就使用和維護了二級緩存(哪怕你出於某種原因希望使用也不行).因此,在使用二級緩存時進行一定的控制還是必要的,Session就提供了設置使用二級緩存的模式的方法(setCacheMode)來實現,當session調用某個方法時對二級緩存的存取改變.

  1.實體類:


 Student.java
  public class Student {
  private Integer id;
  private String name;
  //一系列的setter.getter方法
  }

  2.映射文件:

  Student.hbm.xml


  <class name="com.sxt.hibernate.cache.entity.Student" table="sxt_hibernate_student">

<!-- 指定本類的對象使用二級緩存(這也可以放在hibernate.cfg.xml中統一指定) -->
<!--
<cache usage="read-only"/>
-->
<id name="id" length="4">
<generator class="native"></generator>
</id>
<property name="name" length="10"></property>
</class>

  3. 二級緩存配置文件:

  ehcache.xml


  <ehcache>
<!-- 當二級緩存溢出時,對象保存的臨時磁碟路徑 -->
<diskStore path="java.io.tmpdir"/>

<!--name="sampleCache2" 緩存名字
maxElementsInMemory="1000" 緩存里可存放的最大對象數.
eternal="true" 緩存對象是否永久有效(true表示是).
timeToIdleSeconds="120" 對象在緩存中存活的空閑時間,即空閑多久它就失效,單位是秒.
timeToLiveSeconds="120" 對象在緩存中存活的時間,單位是秒.
overflowToDisk="true" 當緩存溢出時,對象是否保存到磁碟上.保存的磁碟路徑由<diskStore>中的path指定.
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>

  4.hibernate配置文件

  hibernate.cfg.xml


<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL10</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">yf123</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.show_sql">true</property>

<!-- 開啟二級緩存,其實hibernate默認就是開啟的,這裡顯示的指定一下 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定二級緩存產品的提供商 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

<mapping resource="com/sxt/hibernate/cache/entity/Student.hbm.xml"/>

<!-- 指定那些類使用二級緩存 -->
<class-cache usage="read-only" class="com.sxt.hibernate.cache.entity.Student"/>
</session-factory>
</hibernate-configuration>

 


[火星人 ] hibernate的二級緩存介紹已經有919次圍觀

http://coctec.com/docs/java/show-post-60568.html