【发布时间】:2016-11-03 05:18:16
【问题描述】:
我在 Hibernate 中使用 Java 8 和 Spring Data JPA。我正在观察一种奇怪的行为。
所有实体关系都是 LAZY 加载的。
Course toBeMatched = //...a repository call to get a course...;
for (Student s : college.getStudents()) {
if (s.getCourse().equals(toBeMatched)) {
found = true;
}
}
我的equals() 方法返回false,即使是真正的案例。 Course#equals 的实现大致是这样的:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
Course other = (Course) obj;
if (shortName == null) {
if (other.shortName != null)
return false;
} else if (!shortName.equals(other.shortName))
return false;
return true;
}
问题:
我的问题是shortName.equals(other.shortName) 错误地失败了,因为other.shortName 总是null,但是,如果我使用other.getShortName(),我会正确地得到值。
我的问题是,通过访问延迟加载实体的字段而不是通过它的 getter 方法,我是否在做任何根本性的错误。
【问题讨论】:
-
这就是你在使用 Hibernate 时得到的,使用代理而不是字节码增强,因此它对延迟加载字段一无所知,因为它无法检测到它们的使用。打开字节码增强或使用开箱即用的 JPA 提供程序
标签: java hibernate jpa spring-data