我正在使用 Java 8 和 Spring Data JPA 以及 Hibernate。我观察到一种奇怪的行为。
所有实体关系都是惰性加载的。
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 ORM 返回代理对象和延迟加载以支持缓存并提高性能。目前没有办法拦截对 Proxy 字段的调用,因此 other.shortName
将始终为 null
,唯一的方法是拦截对 Proxy 方法的调用。就像您的情况一样, other.getShortName()
就是执行此操作的方法。
关于java - JPA - 延迟加载的实体引用的字段为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394332/