Skip to content

Commit 522b897

Browse files
committed
add section about equals()/hashCode()
1 parent 7465017 commit 522b897

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

documentation/src/main/asciidoc/reference/introduction.adoc

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,44 @@ values!
413413
When you use Hibernate Reactive in Quarkus, these requirements are relaxed,
414414
and you can use public fields instead of getters and setters if you prefer.
415415

416+
=== `equals()` and `hashCode()`
417+
418+
Entity classes should override `equals()` and `hashCode()`. People new to
419+
Hibernate or JPA are often confused by exactly which fields should be
420+
included in the `hashCode()`, so please keep the following principles in
421+
mind:
422+
423+
- You should not include mutable fields in the hashcode, since that would
424+
require rehashing any collection containing the entity whenever the field
425+
is mutated.
426+
- It's not completely wrong to include a generated identifier (surrogate
427+
key) in the hashcode, but since the identifier is not generated until
428+
the entity instance is made persistent, you must take great care to not
429+
add it to any hashed collection before the identifier is generated. We
430+
therefore advise against including any database-generated field in the
431+
hashcode.
432+
433+
It's OK to include any immutable, non-generated field in the hashcode.
434+
435+
TIP: We therefore recommend identifying a _natural key_ for each entity,
436+
that is, a combination of fields that uniquely identifies an instance of
437+
the entity, from the perspective of the data model of the program. The
438+
business key should correspond to a unique constraint on the database,
439+
and to the fields which are included in `equals()` and `hashCode()`.
440+
441+
That said, an implementation of `equals()` and `hashCode()` based on the
442+
generated identifier of the entity can work _if you're careful_.
443+
444+
IMPORTANT: If you can't identify a natural key, it might be a sign that
445+
you need to think more carefully about some aspect of your data model.
446+
If an entity doesn't have a meaningful unique key, then it's impossible
447+
to say what event or object it represents in the "real world" outside
448+
your program.
449+
450+
Note that even when you've identified a natural key, we still recommend
451+
the use of a generated surrogate key in foreign keys, since this makes
452+
your data model _much_ easier to change.
453+
416454
=== Identifier generation
417455

418456
One area where the functionality of Hibernate Reactive diverges from plain

0 commit comments

Comments
 (0)