session中load的get的关系
一、load方法
Configuration cfg = new AnnotationConfiguration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Student student =(Student)session.load(Student.class, 1);
System.out.println(student.getId()+""+student.getName()+""+student.getAge());
session.getTransaction().commit();
session.close();
解释:该段代码作用,取出主键为1的对象,并赋值给一个Student对象。如果把system语句放在commit()之后会出现以下错误
09:11:59,048 ERROR LazyInitializationException:42 - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy noSessionatorg.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.demo_1.Student_$$_javassist_0.getName(Student_$$_javassist_0.java)
at com.test.StudentTest_load.main(StudentTest_load.java:21)
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.demo_1.Student_$$_javassist_0.getName(Student_$$_javassist_0.java)
at com.test.StudentTest_load.main(StudentTest_load.java:21)
错误原因:
Student student =(Student)session.load(Student.class, 1);
在执行这段代码的时候,在数据库中并没有执行sql语句,得到Student对象,而是在用到Student对象的时候才会执行sql语句,所以在事物提交之后就不能再执行sql语句了,所以没有得到Student对象,几报错了。这就是load()方法的特点,用到时再执行sql。
二、get方法
Configuration cfg = new AnnotationConfiguration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Student student =(Student)session.get(Student.class, 1);
session.getTransaction().commit();
System.out.println(student.getId()+""+student.getName()+""+student.getAge());
session.close();
解释:不论system语句放在什么位置,都不会出错,因为在执行
Student student =(Student)session.get(Student.class, 1);
句话的时候,就执行sql语句,并得到Student类的实例对象。