What exactly recognise .equals() method in assumption: object's instance or object's state?
I am learning Hibernate and JPA. When I want to use bidirectional OneToMany association there is a problem because when I override equal and HashCode method with all variables there is become infinity loop. The only way to solve the problem which I see is to not use in one of the class the other class instance in equals() and hashCode(). So I am considering if it is compatible with assumptions in Java for .equals() method.
For example we have a Person class(). I know that email is unique value. So I can compare person by email and then I know that it is the same person (instance) but I don't know if the object's state is the same (firstName and lastName fields can differ). So it is my question, what should we expect during compare object with .equals()?
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email="";
private String firstName = "";
private String lastName = "";
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
return email.equals(person.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
}
When I think of implementing equals
for a given class I ask myself a question: what makes an object unique? What differs instance of one Person
different from other? Then I use that properties for implementing equals
. In your case, or in case of @Entity
objects with @XtoY
relationship, in my opinion there is no need to include this relationship to equals
.
If for example I have a Person
that has a relation to Department
, the fact that a person belongs to some departments doesn't make his unique. It's his name/surname/PESEL or email and so on, and that's what I would include in equals
.
Hope this helps.