我遇到了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()方法之后立即点击数据库,检查这个源代码..
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
你能告诉我哪里出错吗?谢谢。
答案 0 :(得分:2)
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传递给您的load方法,并且因为您的持久化上下文中没有对象,因此它正在查询数据库以使您的s2更新具有持久性状态。
执行以下操作不会立即发出数据库读取: -
Student s2 = session.load(Student.class, new Integer(107));
答案 1 :(得分:2)
您的第一个示例的输出与示例代码不匹配,但我可以看到以下问题:
您正在调用session.get(),它将返回该对象,但您忽略了结果。 试试这个:
System.out.println("Student is calling with get()");
Student s1 = (Student) session.get(Student.class,new Integer(107));
System.out.println("Student called with get()");
System.out.println("Printing Student Name___"+s1.getMarks());
与load()示例类似。第一个参数应该是您要读取的对象的类。该调用将返回该对象。
在这两种情况下都不需要创建new Student()
,Hibernate会为你做这件事。
有关get()和load()的更多信息,请参阅Hibernate: Difference between session.get and session.load