延迟加载:
只有当使用以实体对象的属性(除主键属性外)时,才会发送查询语句到数据库
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的作用域内有效
时间: 2024-10-14 00:51:52