1

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??

VB_
  • 45,112
  • 42
  • 145
  • 293
  • Have you implemented the equals and hashCode methods for Address class?? If yes, post your code here. – Vaibhav Raj Nov 04 '13 at 11:33
  • 1
    Hibernate has nothing to do with the method call `list.contains`. if `equals` is implemented properly, it will return true. – Debojit Saikia Nov 04 '13 at 11:35
  • only equals() method. Do I need hashCode()? – VB_ Nov 04 '13 at 11:44
  • See http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java – Don Roby Nov 04 '13 at 12:10
  • yes, but it doesn't explain why my equals method isn't called at all/ never. – VB_ Nov 04 '13 at 12:22
  • 2
    Try debugging your code and set break point in equals method. If you can post your equals method, it would help us identify the reason behind it. – Vaibhav Raj Nov 04 '13 at 12:29
  • Yes ) I've created my topic only after checking it in debug. You can see my equals method in _EDIT_ section of my question – VB_ Nov 04 '13 at 13:01

1 Answers1

0

What about overriding the equals() method for an Address class and then use the normal ArrayList#contains() as that uses the equals() to evaluate if two objects are the same.

blackpanther
  • 10,998
  • 11
  • 48
  • 78