首页 > 代码库 > hibernate之4.延迟载入

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



hibernate之4.延迟载入