What I have:
I have one-to-many relationship between Person and Adress entities.
@Entity
class Person {
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "person_id")
private List<Address> addresses;
...
}
What I need:
I need to check if specific address has been modified. So, I do
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
}
What a problem
Hibernate DOESN'T CALL equals() method of Address entity! Seems it just compare entity's ids.
Question:
How could force List.contains use overriden equals() method?
EDIT
@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;
}
Answer:
Despite the fact I know the reason know, I still can't grasp it. So the reason is: Address collection has a LAZY fetch type, means Hibernate didn't have time to load it.
But there is still one question:
It is easy to figure out why it doesn't call equals() method, BUT WHY that lazy-collection's contains() method always returns true??