[英]JPA - Lazily loaded entity reference has its fields null
我在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 ORM返回代理對象和延遲加載以支持緩存並提高性能。 當前沒有辦法攔截對Proxy字段的調用,因此other.shortName
始終為null
,唯一的辦法是攔截對Proxy方法的調用。 就像您的情況一樣, other.getShortName()
是執行此操作的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.