hibernate中session的load和get方法

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类的实例对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值