hibernate中session的load和get方法
2016-04-01 09:20
916 查看
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类的实例对象。
相关文章推荐
- 数据中显示"刚刚、几天前、几天前、几个月"等个人的想法
- android: 从相册中选择照片
- SSL常用专业缩略语汇总
- 自己动手丰衣足食之征服jQuery插件编写
- Android 内存分析
- js获取项目路径
- Ubuntu更换bash为zsh
- 查询语句SqlServer与Excel数据导入导出
- P2P 行业解决方案
- 实例讲解iOS应用开发中UIPickerView滚动选择栏的用法
- (OK) android——Repo sync cm—解决—error
- bzoj 4383: [POI2015]Pustynia 线段树优化建图
- phpexcel的使用
- Hello China操作系统在Virtual PC上的安装和使用
- JAVA读取配置文件
- P2P 行业解决方案
- Tempter of the Bone
- Tempter of the Bone
- Hello China操作系统在Virtual PC上的安装和使用
- Hello China操作系统在Virtual PC上的安装和使用