Java JPA-延迟加载的实体引用的字段为空

Java JPA-延迟加载的实体引用的字段为空,java,hibernate,jpa,spring-data,Java,Hibernate,Jpa,Spring Data,我在Hibernate中使用Java8和SpringDataJPA。我观察到一种奇怪的行为 所有实体关系都是延迟加载的 Course toBeMatched = //...a repository call to get a course...; for (Student s : college.getStudents()) { if (s.getCourse().equals(toBeMatched)) { found = true; } } 我的equals()方法返回f

我在Hibernate中使用Java8和SpringDataJPA。我观察到一种奇怪的行为

所有实体关系都是延迟加载的

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返回代理对象和延迟加载以支持缓存并提高性能。目前无法拦截对代理字段的调用,因此
其他。shortName
将始终为
null
,唯一的方法是拦截对代理方法的调用。就像在您的例子中一样,
other.getShortName()
就是这样做的。

Hibernate ORM返回代理对象和延迟加载,以支持缓存并提高性能。目前无法拦截对代理字段的调用,因此
其他。shortName
将始终为
null
,唯一的方法是拦截对代理方法的调用。就像在您的例子中一样,
other.getShortName()
就是这样做的。

这就是使用Hibernate时得到的结果,使用代理而不是字节码增强,因此它对延迟加载字段一无所知,因为它无法检测它们的使用情况。启用字节码增强或使用JPA提供程序进行即时增强这是使用Hibernate时得到的结果,使用代理而不是字节码增强,因此它对延迟加载字段一无所知,因为它无法检测它们的使用情况。启用字节码增强,或者使用一个JPA提供程序来实现它