hibernate的懶載入
在之前的基礎上測試懶載入與普通載入的區別冬眠的懶載入
物件的三種狀態對於Hibernate而言,物件的狀態分為3種:
1)暫時態當物件剛建立,和會話沒有發生任何關係時,當程式執行完就立刻消失,被稱為暫時態。
2)持久態當執行如下程式碼時,物件變為持久態Emp e = new Emp();
session.save(); 持久態的物件和會話發生了關係,如執行了儲存,獲取,查詢等方法
Session中會快取該物件(Session的快取即一級快取)
會話再獲取物件時,首先去查詢一級快取,如果沒有才查詢資料庫
會議要負責將持久態物件的變化更新到資料庫(在是flush()的時候更新,tx在提交的時候會自動呼叫session的flush())
3)遊離態呼叫了session.evict(Object obj)方法,和Session解除了關係
冬眠懶載入
懶惰載入懶惰 ?
懶載入又稱延遲載入,
原理:當訪問實體物件是,並不是立即到資料庫中查詢而是在真正要使用實體物件時,才到資料庫中的查詢資料,儘可能晚的將資料庫的資料載入到記憶體來,作用提高應用的執行效能。
延遲載入的應用:session.Load()query.iterate()以及關聯查詢,這些方法返回的物件,裡面沒有資料,資料在用的時候(呼叫get()方法時),才取好處:不得,不查詢資料庫
驗證一級快取的存在 s.evict(學生); //從資料庫中查詢放到會話快取中,s.evict清除快取,清空,現在快取沒有
//驗證一級快取的存在 @Test public void testExist() { Session s = openSession(); Student student = (Student) s.get(Student.class, 2); System.out.println(student.toString()); System.out.println("----------------------------"); s.evict(student); //從資料庫中查詢放到session快取中,s.evict清除快取,清空,現在快取沒有 //再次查詢是,快取中沒有,到資料庫查詢 Student st1 = (Student) s.get(Student.class, 2); System.out.println(st1.toString()); System.out.println("-----------------"); System.out.println(st1==student); }
測試結果為假,第一次查詢後,使用逐出()清空快取,再次查詢的時候快取中不存在,重新再資料庫中查詢,這樣的他們的物理儲存空間就不相同了,則為假
在之前的基礎上測試懶載入與普通載入的區別
//驗證懶載入的原理(get 不進行懶載入。load進行懶載入
@Test
public void testLazy() {
Session s=openSession();
Student student = (Student) s.get(Student.class, 2);//進行查詢
System.out.println("-------------------");
System.out.println(student.toString());
}
@Test
public void testLazy2() {
Session s=openSession();
Student student = (Student) s.load(Student.class, 2); //執行到這,不做查詢
System.out.println("----------------------");
System.out.println(student.toString());
s.close();
}
這裡需要注意分隔符的位置,因為在get()方法中,學生=(學生)s.get(Student.class,2); //進入資料庫進行查詢
而負載()的方法執行,的System.out.println(student.toString());這裡才執行