Hibernate緩衝機制執行個體代碼解析,hibernate緩衝

來源:互聯網
上載者:User

Hibernate緩衝機制執行個體代碼解析,hibernate緩衝

本文研究的主要是Hibernate緩衝機制的相關內容,具體如下。

示範項目:

Student.java:

public class Student {/*學生ID*/private int id;/*學生姓名*/private String name;/*學生和班級的關係*/private Classes classes;//省略setter和getter方法}

Classes.java:

public class Classes {/*班級ID*/private int id;/*班級名稱*/private String name;/*班級和學生的關係*/private Set<Student> students;//省略setter和getter方法}

Student.hbm.xml:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.lixue.bean">   <class name="Student" table="t_student">     <id name="id">       <generator class="native"/>     </id>     <!-- 映射普通屬性 -->     <property name="name"/>     <!-- 多對一 映射,在多的一端加上外鍵-->     <many-to-one name="classes" column="classesid"/>   </class> </hibernate-mapping> 

Classes.hbm.xml:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.lixue.bean">   <!-- 設定lazy為false -->   <class name="Classes" table="t_classes" lazy="false">     <id name="id">       <generator class="native"/>     </id>     <property name="name"/>     <!-- 一對多映射 ,inverse="true"表示交給對端維護關係-->     <set name="students" inverse="true">        <key column="classesid"/>       <one-to-many class="Student"/>     </set>   </class> </hibernate-mapping> 
一級緩衝:

一級緩衝聲明周期很短和session的生命週期一致,一級緩衝也叫session級的緩衝或事物級緩衝,一級緩衝是緩衝對象的,並不能緩衝屬性。

測試方法(在同一個session中使用load()查詢兩次):

/*取出來之後會放在緩衝中,第二次取的時候會直接從緩衝取出*/       Student student = (Student)session.load(Student.class, 1);       System.out.println("student.name=" + student.getName());              /*不會發出查詢語句,load使用緩衝*/       student = (Student)session.load(Student.class, 1);       System.out.println("student.name=" + student.getName()); 

註:我們會發現,當我們第一次查詢的時候,查出來的結果是會放在session即緩衝即一級緩衝中的。第二次load()後及時去擷取值的時候也沒有在發出語句到資料庫中查詢了,而是直接從緩衝中取值了(必須是在同一session中)。

測試方法二(在同一session中):

Student student = new Student();       student.setName("張三");       Serializable id = session.save(student);       student = (Student)session.load(Student.class, id);       //不會發出查詢語句,因為save支援緩衝       System.out.println("student.name=" + student.getName()); 

註:調用了save()方法再使用load()去載入對象,然後真正擷取name屬性,但是此時並不會發出語句去查詢資料庫。因為save()方法也是支援緩衝的。

測試大批量資料的添加:

public void testCache7() {     Session session = null;     try {       session = HibernateUtils.getSession();       session.beginTransaction();       for (int i=0; i<100; i++) {         Student student = new Student();         student.setName("張三" + i);         session.save(student);         //每20條更新一次         if (i % 20 == 0) {           //清除緩衝,調用flush之後資料就會儲存到資料庫           session.flush();           //清除緩衝的內容           session.clear();         }       }       session.getTransaction().commit();     }catch(Exception e) {       e.printStackTrace();       session.getTransaction().rollback();     }finally {       HibernateUtils.closeSession(session);     }   } 

註:

1.因為save()方法支援緩衝,那就存在一個問題,如果我要同時存1000萬條資料,那緩衝中豈不是有1000萬的緩衝對象,那就很可能導致溢出。所以說Hibernate並不能很好的支援大批量資料的更新操作,但是我們也可以很靈活的處理這個問題,比如使用迴圈每20條資料清除一次緩衝。

2.save,update,saveOrUpdate,load,get,list,iterate,lock這些方法都會將對象放在一級緩衝中,一級緩衝不能控制緩衝的數量,所以要注意大大量操作資料時可能造成記憶體溢出;可以用evict,clear方法清除緩衝中的內容。

二級緩衝:

二級緩衝也稱為進程級緩衝或SessionFactory級緩衝,二級緩衝可以被所有的session緩衝共用。二級緩衝的生命週期和SessionFactory的生命週期一致,SessionFactory可以管理二級緩衝,二級緩衝的原則是當讀遠大於寫的時候使用,二級緩衝也主要是緩衝實體物件的。

二級緩衝的配置:

1.將ehcahe.xml檔案拷貝到src目錄下。

2.在Hibernate.cfg.xml檔案中加入緩衝產品供應商,如下:

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

3.啟用二級緩衝(可以不顯示啟動,因為預設就是啟用的),如下:

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

4.指定哪些實體類使用二級緩衝。

5.匯入緩衝使用的介面jar包:lib\optional\ehcache\ehcache-core-2.4.3.jar

ehcache.xml檔案的內容:

<defaultCache     maxElementsInMemory="10000"     eternal="false"     timeToIdleSeconds="120"     timeToLiveSeconds="120"     overflowToDisk="true"     /> 

註:

1.maxElementsInMemory表示緩衝中最多存放的對象。

2.eternal表示是否永遠不到期(設定為false更有實際意義,如果為true的話表示永遠不到期,那麼下面的屬性都沒什麼意義了)。

3.timeToIdleSecods表示一個對象第一次被訪問後經過多長時間沒被訪問就清除。

4.timeToLiveSecods表示一個對象的存貨時間。

5.overflowToDisk為true表示緩衝中超出了maxElementsInMemory指定的個數就存到磁碟中。

指定溢出時儲存的磁碟路徑:

<diskStore path="java.io.tmpdir"/>

註:這個路徑可以改。

測試方法(一級緩衝的前提是必須在同一個session,現在我們使用二級緩衝來看看在兩個不同的session中是否存在緩衝):

public void testCache1() {Session session = null;try {session = HibernateUtils.getSession();session.beginTransaction();Student student = (Student)session.load(Student.class, 1);System.out.println("student.name=" + student.getName());session.getTransaction().commit();}catch(Exception e) {e.printStackTrace();session.getTransaction().rollback();}finally {HibernateUtils.closeSession(session);}try {session = HibernateUtils.getSession();session.beginTransaction();Student student = (Student)session.load(Student.class, 1);//不會發出查詢語句,因為配置二級緩衝,session可以共用二級緩衝中的資料 //二級緩衝是進程級的緩衝 System.out.println("student.name=" + student.getName());session.getTransaction().commit();}catch(Exception e) {e.printStackTrace();session.getTransaction().rollback();}finally {HibernateUtils.closeSession(session);}}

註:如果配置了二級緩衝,我們會發現,即使第一個session關閉了,再開啟另外一個session去載入資料也不會發出語句到資料庫中去查詢資料,因為配置了二級緩衝,它是整個sessionFactory共用的。

禁用二級緩衝實現大批量資料的添加:

public void testCache5() {     Session session = null;     try {       session = HibernateUtils.getSession();       session.beginTransaction();              //禁止一級緩衝和二級緩衝互動       session.setCacheMode(CacheMode.IGNORE);       for (int i=0; i<100; i++) {         Student student = new Student();         student.setName("張三" + i);         session.save(student);         //每20條更新一次         if (i % 20 == 0) {           session.flush();           //清除緩衝的內容           session.clear();         }       }       session.getTransaction().commit();     }catch(Exception e) {       e.printStackTrace();       session.getTransaction().rollback();     }finally {       HibernateUtils.closeSession(session);     }   }  

註:session.flush()表示清除一級緩衝,但是我們又開起了二級緩衝,save()之後也儲存到了二級緩衝,還是存在緩衝過大導致溢出的情況。所以這種情況下我們應該禁用二級緩衝:session.setCacheMode(CacheMode.IGNORE);

查詢快取:一級緩衝和二級緩衝都是緩衝實體物件的,但是有些時候我們希望擷取某些屬性的時候也不要頻繁的去訪問資料庫,而是從緩衝中擷取,此時我們就可以使用查詢快取。另外查詢快取對實體物件的結果集會緩衝ID。查詢快取的生命週期,當關聯的表發生修改,查詢快取的聲明周期就結束,和session的生命週期無關。

配置查詢快取:

1.修改hibernate.cfg.xml檔案,來開啟查詢快取,預設是false即不開啟的,應如下設定:

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

2.必須在程式中啟用,如:

query.setCacheable(true) 

測試方法:

public void testCache2() {Session session = null;try {session = HibernateUtils.getSession();session.beginTransaction();List names = session.createQuery("select s.name from Student s")                 .setCacheable(true)                 .list();for (int i=0; i<names.size(); i++) {String name = (String)names.get(i);System.out.println(name);}session.getTransaction().commit();}catch(Exception e) {e.printStackTrace();session.getTransaction().rollback();}finally {HibernateUtils.closeSession(session);}System.out.println("-------------------------------------------------------");try {session = HibernateUtils.getSession();session.beginTransaction();//不會發出查詢語句,因為查詢快取和session的生命週期沒有關係 List names = session.createQuery("select s.name from Student s")                 .setCacheable(true)                 .list();for (int i=0; i<names.size(); i++) {String name = (String)names.get(i);System.out.println(name);}session.getTransaction().commit();}catch(Exception e) {e.printStackTrace();session.getTransaction().rollback();}finally {HibernateUtils.closeSession(session);}}

註:上述代碼中,我們關閉了二級緩衝,開啟了查詢快取,然後查詢普通屬性。運行測試代碼我們可以發現,在第一個session中第一次查詢發出了一條語句,然後關閉了session,接著再第二個session中進行查詢,我們會發現第二個session中的查詢並沒有發出語句,這說明查詢快取和session的生命週期沒有什麼關係。

hibernate.cfg.xml的緩衝配置:

<!-- 設定指定二級緩衝的實現介面 -->     <property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>     <!-- 設定二級緩衝所使用的設定檔 -->     <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>     <!-- 設定使用QUERY查詢快取 -->     <property name="hibernate.cache.use_query_cache">true</property>          <!-- 載入對象關係對應檔 -->     <mapping resource="com/lixue/bean/Classes.hbm.xml" />     <mapping resource="com/lixue/bean/Student.hbm.xml" />          <!-- 必須先引入資源地圖檔案(就是實體對應檔)後再設定有使用二級緩衝的實體類 -->     <class-cache usage="read-only" class="com.lixue.bean.Student" /> 
總結

以上就是本文關於Hibernate緩衝機制執行個體代碼解析的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.