【问题标题】:JPA - Lazily loaded entity reference has its fields nullJPA - 延迟加载的实体引用的字段为空
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2011-10-02
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多