Hibernate: When is it necessary to implement equals() and hashCode(), and if so, how?

后端 未结 2 570
灰色年华
灰色年华 2021-01-02 17:40

Based on various bad experiences my rule of thumb as a Java programmer is to only implement equals() and hashCode() on immutable objects, where two

2条回答
  •  心在旅途
    2021-01-02 17:53

    What semantics does JPA/Hibernate impose?

    The JPA specification says the following.

    2.4 Primary Keys and Entity Identity

    Every entity must have a primary key. ... The value of its primary key uniquely identifies an entity instance within a persistence context and to EntityManager operations

    I interpret that as saying the semantics of equivalence for JPA entities is equivalence of primary keys. That suggests the equals() method should compare the primary keys for equivalence, and nothing else.

    But the Hibernate advice you reference (and another article I've seen) say not to do that, but rather to use a "business key" rather than the primary key. The reason for this seems to be because we can not guarantee that an entity object has a value for a generated primary key until the entity has been synchronized (using EntityManager.flush()) to the data-base.

提交回复
热议问题