hibernate之4.延迟载入

Posted yangykaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.延迟载入的主要内容,如果未能解决你的问题,请参考以下文章

HIbernate学习笔记4 之 延迟加载和 关联映射

javaitoo项目实战之hibernate 懒载入优化性能

Hibernate之抓取策略

Hibernate检索策略之延迟加载和立即加载

hibernate 的 关联关系之多对多 和 延迟加载

延迟加载问题:Hibernate 3、Spring 4、Jackson 2.4.0