hibernate之4.延遲載入
阿新 • • 發佈:2017-06-11
pop not in 異常 .get pos pan 實體對象 content except
延遲載入:
僅僅有當使用以實體對象的屬性(除主鍵屬性外)時,才會發送查詢語句到數據庫
get不支持延遲載入
@Test public void getTest(){ Session session=null; Student student=null; try{ session=HibernateUtil.openSession(); student=(Student) session.get(Student.class, 3); System.out.println("id:"+student.getStudentId()); System.out.println("name:"+student.getStudentName()); }finally{ session.close(); } }
結果:Hibernate: select student0_.student_id as student1_0_0_, student0_.student_name as student2_0_0_, student0_.age as age0_0_ from t_student student0_ where student0_.student_id=? id:3 name:ddddd
在調用get方法時,就已經發出查詢語句
load支持延遲載入
@Test public void loadTest(){ Session session=null; Student student=null; try{ session=HibernateUtil.openSession(); student=(Student) session.load(Student.class, 3); System.out.println("id:"+student.getStudentId()); System.out.println("name:"+student.getStudentName()); }finally{ session.close(); } }
結果:id:3 Hibernate: select student0_.student_id as student1_0_0_, student0_.student_name as student2_0_0_, student0_.age as age0_0_ from t_student student0_ where student0_.student_id=? name:ddddd
在調用load方法,返回一個代理對象,此時並沒有發出查詢語句,當須要使用studentName屬性時,再發出查詢語句
關閉session後
get:
@Test public void get2Test(){ Session session=null; Student student=null; try{ session=HibernateUtil.openSession(); student=(Student) session.get(Student.class, 3); }finally{ session.close(); } System.out.println("id:"+student.getStudentId()); System.out.println("name:"+student.getStudentName()); }
結果:Hibernate: select student0_.student_id as student1_0_0_, student0_.student_name as student2_0_0_, student0_.age as age0_0_ from t_student student0_ where student0_.student_id=?id:3 name:ddddd
與在session作用域中的結果一樣
load
@Test public void load2Test(){ Session session=null; Student student=null; try{ session=HibernateUtil.openSession(); student=(Student) session.load(Student.class, 3); }finally{ session.close(); } System.out.println("id:"+student.getStudentId()); System.out.println("name:"+student.getStudentName()); }
結果:id:3 org.hibernate.LazyInitializationException: could not initialize proxy - no Session
拋異常了,可見延時載入僅僅在session的作用域內有效
小結:
1.僅僅有當使用以實體對象的屬性(除主鍵屬性外)時,才會發送查詢語句到數據庫
2.延時載入僅僅在session的作用域內有效
hibernate之4.延遲載入