javajpaentityequalshashcode

Should I write equals() and hashCode() methods in JPA entities?


I want to check if entity is in a Collection member (@OneToMany or @ManyToMany) of another entity:

if (entity2.getEntities1().contains(entity1)) { }

Solution

  • Not necessarily. There are three options:

    See this article for more details. Also note that equals() and hashCode() are tied and should be implemented both with exactly the same fields.