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

后端 未结 6 1862
说谎
说谎 2020-11-28 19:35

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

if (entity2.getEntities1().conta         


        
6条回答
  •  执笔经年
    2020-11-28 20:28

    We tend to let IDE generate hashCode() and equals() for us. Be careful though. When you generate those methods for JPA Entities. Some versions of equals() checks for class identity

    // ... inside equals() - wrong approach for Entities (cause of generate proxies)
    if (o == null || this.getClass() != o.getClass()) {
            return false;
    }
    // ...
    

    This would break your collections with some JPA libraries as those libraries create proxies to your entities (subclasses), like for example MyGreatEntity_$$_javassist_7 in Hibernate.

    In Entities always allow subclasses in equals().

提交回复
热议问题