在休眠中使用 get() 和 load() 函数时无法理解输出

Not able to understand output while using get() and load() function in hibernate

我有一个学生 table 有主键 ID。我正在使用 Hibernate 和会话的加载命令来获取记录。我正在获取 ID 1 和 2 的记录都不存在于数据库中。我知道在这种情况下 get() returns null 和在这种情况下 load() returns ObjectNotFoundException() 。但是我得到了一个奇怪的输出。

Student student1 = session.get(Student.class, 1);
System.out.println(student1);
Student student2 = session.load(Student.class, 2);
System.out.println("ABC");
System.out.println(student2);

我得到的输出 -

null
ABC
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]

我期待的输出 -

null
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]

这里有什么我没说到的吗?

如果您使用 session.load() 加载一个实体,并且在之前的同一事务中未使用 session.get() 检索该实体,它将 return 您一个未初始化的代理,它是它的预期的行为。

由于 returned 代理未初始化,在 session.load() 期间没有数据库访问,因此即使 ID 无效,也不会在这段时间内抛出 ObjectNotFoundException

如果您在那之后访问实体的属性而不是它的 ID,它只会 select 来自数据库的记录来实际初始化代理 (1) .在初始化代理期间,如果发现此 ID 不存在 DB 记录,它将抛出 ObjectNotFoundException。现在您在打印时通过其 toString() 访问 student2 的属性,因此当时抛出 ObjectNotFoundException

另请参阅我大约 10 年前在 here.

上关于 session.get()session.load() 之间差异的回答

注(1):行为实际上是由配置hibernate.jpa.compliance.proxy定义的。详情请见it