Hibernate單表操作(六)——查詢記錄get()與load()方法區別
阿新 • • 發佈:2018-12-29
在上一次的案例中,通過get或者load方法得到的結果一樣。
既然得到的結果一樣,
那麼 get和load方法查詢記錄的區別是什麼呢?
區別一:
在不考慮快取的情況下,get方法會在呼叫之後立即向資料庫發出sql語句,發出selelct語句,去查詢這個記錄或者說物件,返回本身的持久化物件。
load方法會在呼叫後返回一個代理物件。
該代理物件只儲存了實體物件的主鍵id,直到真正使用物件的非主鍵屬性時才會發出sql語句。
區別二:
查詢資料庫中不存在的資料庫時,get方法返回null。
load方法丟擲異常:org.hibernate.ObjectNotFoundException
用程式碼來測試說明以上兩點:
@Test
public void testGetStudents(){
Students s=(Students) session.get(Students.class,1);
System.out.println(s.getClass().getName());
//System.out.println(s);
}
測試結果(控制檯輸出):
注意了注意了,這裡我已經把
System.out.println(s);
語句註釋掉了。但是還是會發出sql語句。
繼續測試:
@Test public void testLoadStudents(){ Students s=(Students) session.load(Students.class,1); System.out.println(s.getClass().getName()); //System.out.println(s); }
測試結果:
這裡我也把那條輸出語句註釋了,但是因為這時候沒有必要使用非主鍵屬性,所以並沒有發出sql語句。這就是load方法的特點。
其次,輸出的類名就不是真正的類名。是代理物件對應的類名。所以並不是一個持久化物件。
再進行測試驗證不存在的返回值情況:
@Test public void testGetStudents(){ Students s=(Students) session.get(Students.class,10); //System.out.println(s.getClass().getName()); System.out.println(s); }
現在將查詢的主鍵序列改為了10,因為資料庫中沒有該主鍵對應的記錄。所以get()方法會返回null。
而如果使用load方法,會出現異常!
@Test
public void testLoadStudents(){
Students s=(Students) session.load(Students.class,10);
//System.out.println(s.getClass().getName());
System.out.println(s);
}
測試結果:
只發出了sql語句,但是沒有返回任何東西,異常資訊如下:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [Entity.Students#10]
大概的意思就是:找不到物件。所給的識別符號10,並不存在(那一行)。