我有的:
我在 Person 和 Adress 实体之间有一对多的关系。
@Entity
class Person {
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "person_id")
private List<Address> addresses;
...
}
我需要的:
我需要检查特定地址是否已被修改。所以,我愿意
if (address.getId() != 0 && !person.getAddresses().contains(address)) {
//this address has already been persisted but one (or more) of it fields have been modified
//than it has been modified
}
有什么问题
Hibernate 不调用地址实体的 equals() 方法!似乎它只是比较实体的ID。
问题:
如何强制 List.contains 使用覆盖的 equals() 方法?
编辑
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof VacancyComment))
return false;
VacancyComment vc = (VacancyComment) o;
if (!(vc.getId() == this.getId()))
return false;
if (!vc.getAuthor().equals(this.getAuthor()))
return false;
if (!vc.getCreated().equals(this.getCreated()))
return false;
if (!vc.getText().equals(this.getText()))
return false;
return true;
}
回答:
尽管我知道原因知道,但我仍然无法掌握它。所以原因是:地址集合有一个 LAZY 提取类型,意味着 Hibernate 没有时间加载它。
但是还有一个问题:
很容易弄清楚为什么它不调用 equals() 方法,但是为什么惰性集合的 contains() 方法总是返回 true?