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
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.