liveBook · Manning

Database identifier equality

As explained in Java Persistence with Spring Data and Hibernate epub

Database identifier equality is an equality strategy that determines object equality solely from a persistent database identifier.

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.

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains identifier assignment, hash changes, Set contract violations, and cascading consequences before recommending business keys.
Examples
Uses User.username equality and cross-context User instances collected in a HashSet.
What you can do after
Evaluate identifier-based equality against business-key equality when designing persistent entities and set-based associations.
How it connects
Connects database identifiers with business keys, surrogate primary keys, equals(), hashCode(), Hibernate, and Java Set semantics.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.