hibernate之4.延迟加载

延迟加载:

只有当使用以实体对象的属性(除主键属性外)时,才会发送查询语句到数据库


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的作用域内有效



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。