我在使用 hibernate load() 和 get() 时面临两个问题
get() 始终返回 NULL,即使该对象存在于数据库中。
Student s1=new Student(); System.out.println("Student is calling with get()"); session.get(Student.class,new Integer(107)); System.out.println("Student called with get()"); System.out.println("Printing Student Name___"+s1.getMarks()); System.out.println("--------------------------------"); Student s2=new Student(); System.out.println("Student is calling with load()"); session.load(s2,new Integer(107)); System.out.println("Student called with load()"); System.out.println("Printing Student Name___"+s2.getStdName());
输出:
Student is calling with load()
Hibernate: select student0_.stdtId as stdtId1_0_, student0_.stdName as stdName1_0_, student0_.marks as marks1_0_ from Student student0_ where student0_.stdtId=?
Student called with load()
Printing Student Name___0.0
--------------------------------
Student is calling with get()
Student called with get()
Printing Student Name___null
但是如果我单独使用 load() 调用同一个对象,它工作正常并给出输出。
正如上面所说,只有当我们调用 load() 的属性时,load() 才会访问数据库,但这里它在调用 load() 方法后立即访问数据库,请检查源代码..
Student s2=new Student(); System.out.println("Student is calling with get()"); session.load(s2,new Integer(107)); System.out.println("Student called with get()"); System.out.println("Printing Student Name___"+s2.getStdName());
输出:
Student is calling with get()
Hibernate: select student0_.stdtId as stdtId1_0_, student0_.stdName as stdName1_0_, student0_.marks as marks1_0_ from Student student0_ where student0_.stdtId=?
Student called with get()
Printing Student Name___Jaswanth
您能建议一下我在哪里犯了错误吗?谢谢。
最佳答案
Hibernate Session.get(..) 返回给定类的持久实体。引用 API Hibernate Session
因此,您需要将返回的持久性实例引用到 Student 类变量,以便获取数据。因此您的代码需要进行以下修改:-
Student s1= null;
System.out.println("Student is calling with get()");
s1 = (Student)session.get(Student.class,new Integer(107));
System.out.println("Student called with get()");
System.out.println("Printing Student Name___"+s1.getMarks());
关于你的第二个疑问,你正在将一个非持久的新对象 s2 传递给你的加载方法,并且由于你的持久上下文中没有对象,所以它正在查询数据库以使你的 s2 更新为持久状态。
执行以下操作不会立即发出数据库读取:-
Student s2 = session.load(Student.class, new Integer(107));
关于java - Hibernate get() 总是返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25904042/