Database identifier equality defines two entity instances as equal when their persistent database identifiers match. A null identifier denotes a transient instance, but Hibernate assigns identifiers only when instances become persistent, creating collection hazards. section 10.3.2
The strategy creates practical problems when entities participate in hashed collections:
- Adding a transient entity to a Set can become invalid after persistence changes its identifier-derived hash value. section 10.3.2
- Changed hash values can break Set membership and make cascading persistence unreliable for set-based mapped associations. section 10.3.2
- A business key, such as a unique username, provides the recommended basis for equals() and hashCode(). section 10.3.2
Equality across persistence contexts
Two User instances loaded with the same database identifier may not be identical with == when loaded through different persistence contexts, but business-key equality can make equals() true and reduce a HashSet to one element.
