Why is it considered the best practice to override the hashCode()
and equals()
methods in a Hibernate persistence class?

- 6,077
- 1
- 32
- 37

- 821
- 2
- 8
- 14
-
Please provide a reference to who says it's a best practice. – chrylis -cautiouslyoptimistic- Aug 23 '16 at 12:17
-
the code quality tools like SONAR,CAST – not-a-bug Sep 10 '20 at 06:24
2 Answers
Hibernate doc:
You have to override the equals() and hashCode() methods if you
intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations) and
intend to use reattachment of detached instances
Hibernate guarantees equivalence of persistent identity (database row) and Java identity only inside a particular session scope. So as soon as we mix instances retrieved in different sessions, we must implement equals() and hashCode() if we wish to have meaningful semantics for Sets.
see this link https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html
Let's consider this scenario to show some of the problems that will occurs if you are using the default implementation of equals and hashcode:
@Entity Parent{
@Id
@GeneratedValue
Long id;
@OneToMany(mappedBy = "parent",
cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="PARENT_ID")
Set<Child> childrens = new HashSet<Child>();
//get+set
}
@Entity Child{
@Id
@GeneratedValue
Long id;
}
test(){
Parent p1 = new Parent();
Child c1 = new Child();
entityManager.persist(p1);
entityManager.persist(c1);
p1.getChilds.add(c1);
entityManager.merge(p);
//!!:using another instance of entitymanager just to simulate the case of detached entities.
Parent p2 =entityManager1.find(p1.getId(),Parent.class);
child c2 =entityManager1.find(c1.getId(),Child.class);
boolean contains=p1.getChilds().contains(c2); // problem1: contains==false
//Then if we add c2 to the childs set we will have
//a duplication inside the Set
p2.getChilds.add(c2);//problem2:childs contains c1 and c2
boolean remove=p2.getChilds.remove(c2);//problem3:remove==false
entityManager1.merge(p2);//problem4: hibernate will deal with c2
//like a new entity then an insert operation is
//triggered on c2 (an exception=> violation of unique id)
}

- 1,615
- 15
- 26
-
so,hashcode() and equals() should be implemented in both entity classes which has one to many relationships where setting a child entity can cause detached instances?? – not-a-bug Sep 09 '20 at 06:25
There is absolutly no reason to override equals
and hashCode
because Hibernate
do not rely on them. It compares entities themself by comparing attributes.

- 17,973
- 3
- 29
- 66
-
Hibernate documentation states otherwise, that you should implement equals() and hashCode() if an entity will be put in a collection that makes use of those methods and if you plan to reattach dettached instances. – Matheus Moreira May 11 '17 at 15:56