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

标签 java hibernate jpa spring-data

我正在使用 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()方法也会返回falseCourse#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/

相关文章:

java - CAS 在 tomcat 上获取 Oracle APEX 的属性

java - 从 Google App Engine 后端检索实体到 Android 应用程序

java - 切换到特定选项卡并关闭其他选项卡

java - 将多个任意注释合并为一个

java - JPA 实体管理器资源处理

Java Enum 值子集线程安全

java - 如何在 Hibernate-Spatial 和 Postgis 中持久保存 MultiPoligon 对象

mysql - hibernate + MySQL : How to set the encoding utf-8 for database and tables

java - 为什么没有 CriteriaQuery<T>#where(List<Predicate>)?

java - Datanucleus在GAE中使用Maven增强,构建失败