HibernateDaoSupper对hibernate的支持
用getHibernateTemplate(),不支持延迟加载,因为它的session一用完就关闭;
用getSession()可以支持延迟加载,而session的关闭也是Spring的事物帮你关闭它.不需要你动手。
例子与区别:
public Instructor findInstructorById(Integer id) {
return (Instructor) getHibernateTemplate().get(Instructor.class, id);
}
public Instructor findInstructorById(Integer id) {
return (Instructor)getSession().get(Instructor.class, id);
}
BeanFactory ac = new FileSystemXmlApplicationContext(
"WebRoot/WEB-INF/applicationContext.xml");
InstructorDao instructorDao=(InstructorDao)ac.getBean("instructorDao");
Instructor instructor=instructorDao.findInstructorById(1);
System.out.println(instructor.getName());
System.out.println(instructor.getCourses().size());
getHibernateTemplate()的结果(出异常了):
Hibernate: select instructor0_.id as id0_0_, instructor0_.name as name0_0_, instructor0_.password as password0_0_ from instructor instructor0_ where instructor0_.id=?
tiger
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.huanglq.model.Instructor.courses, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97)
at org.hibernate.collection.PersistentSet.size(PersistentSet.java:114)
at com.huanglq.test.Test.main(Test.java:41)
getSession()的结果:
Hibernate: select instructor0_.id as id0_0_, instructor0_.name as name0_0_, instructor0_.password as password0_0_ from instructor instructor0_ where instructor0_.id=?
tiger
Hibernate: select courses0_.id as id1_, courses0_.id as id3_0_, courses0_.instructor_id as instructor2_3_0_, courses0_.name as name3_0_, courses0_.state as state3_0_, courses0_.startDate as startDate3_0_, courses0_.endDate as endDate3_0_, courses0_.description as descript7_3_0_, courses0_.maxstudentcount as maxstude8_3_0_ from course courses0_ where courses0_.id=?
Hibernate: select students0_.course_id as course2_1_, students0_.stu_id as stu1_1_, student1_.id as id1_0_, student1_.name as name1_0_, student1_.password as password1_0_, student1_.age as age1_0_, student1_.address as address1_0_, student1_.state as state1_0_, student1_.phone as phone1_0_, student1_.email as email1_0_, student1_.zip as zip1_0_, student1_.description as descrip10_1_0_ from stu_cour students0_ left outer join student student1_ on students0_.stu_id=student1_.id where students0_.course_id=?
1