Entities and relationships
@Entity, identity, @OneToMany and @ManyToOne, owning sides, cascades, and the equals/hashCode that makes an entity safe in a Set.
An @Entity is not a class that can be saved. It is a class whose instances Hibernate watches, and almost every surprise in this course follows from that one word. You do not tell it to write your changes; it notices them. You do not tell it to load a relationship; it fetches when you look. The mapping annotations decide when all of that happens, and the defaults are not the ones you would choose.
This lesson is the mapping. The watching is the next one.
An entity has three identities, not one
Every entity you write has three different notions of "the same", and confusing them is the source of bugs that only appear once the data is real.
- Object identity —
a == b, the same JVM object. - Database identity — the same primary key.
- Business identity — the same ISBN, the same email, the same order number.
Hibernate guarantees the first two line up within one persistence context: load the same row twice in one session and you get the same object back. Outside that, they come apart, and the place they come apart most painfully is a Set.
The equals and hashCode that quietly breaks
Here is the implementation everyone writes first. It is the one your IDE generates, and it is wrong:
@Entity
public class Tag {
@Id @GeneratedValue Long id;
String name;
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tag)) return false;
return Objects.equals(id, ((Tag) o).id);
}
@Override public int hashCode() { return Objects.hash(id); }
}Put one in a HashSet before it is saved, save it, and look again:
### before persist, id = null, set.contains(t) = true
### after persist, id = 1, set.contains(t) = false
### the set still reports size 1, and iterating finds it: javaRead the middle line twice. The set contains that exact object — size() is 1, iterating hands it back — and contains() says no. persist assigned the id, the id changed the hash code, and the object is now sitting in the wrong bucket. Nothing threw. Nothing logged.
The cause is a rule that has nothing to do with JPA: a hash code must not change while the object is in a hash-based collection, and a generated id changes exactly once, at the worst moment.
Three implementations actually work:
| What you use | When it is right |
|---|---|
| a business key — ISBN, email, order number | best, when a real immutable one exists |
| a UUID you assign yourself in the constructor | when there is no business key; the id exists before persist, so it never changes |
getClass() in equals, a constant hashCode() | the pragmatic fallback; correct, and degrades a Set to a list |
That last one looks like cheating and is what Hibernate's own documentation suggests when there is no business key. A constant hash code means every entity lands in one bucket, so lookup is linear — which is fine for the handful of children in a collection and not fine for ten thousand.
The owning side is the only side that matters
A relationship in your object graph is two references. A relationship in the database is one foreign key column. Something has to decide which reference writes that column, and that is the owning side.
mappedBy marks the other one — the inverse side — and the inverse side is read-only. Watch what that means:
Author a = new Author("Bloch");
em.persist(a);
Book b = new Book("Effective Java"); // b.author deliberately not set
a.getBooks().add(b); // only the inverse side touched
em.persist(b);
em.getTransaction().commit();### committing: added to author.books, never set book.author
### the foreign key column in the database is: nullIn memory the object graph is perfect — a.getBooks() has the book in it, and every assertion you write in that method passes. In the database there is no relationship at all. @OneToMany(mappedBy = "author") says Book owns this; I am a view of it, so Hibernate read book.author, found null, and wrote null.
This is why entities carry a helper that sets both sides, and why writing one without the other is the single most common relationship bug:
public void addBook(Book book) {
books.add(book); // the side you read
book.setAuthor(this); // the side that is written
}The fetch defaults are backwards from what you want
Each relationship annotation has a default fetch type, and they are not consistent:
| Annotation | Default | What it means |
|---|---|---|
@ManyToOne | EAGER | loading the child loads the parent, always |
@OneToOne | EAGER | same |
@OneToMany | LAZY | the collection loads when touched |
@ManyToMany | LAZY | same |
The two singular ones default to eager, and that is a decision from 2006 that nobody can change now. Here is what it costs. A Book with an ordinary @ManyToOne Author, no fetch type written anywhere, and a query that loads books and never mentions the author:
### load 8 books. @ManyToOne author is declared with no fetch type.
Hibernate: select book0_.id, book0_.author_id, book0_.title from Book book0_
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=?
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=?
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=?
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=?
### loaded 8 books; not one line of code has touched .getAuthor()Five queries where you asked for one, for data the code never reads. This is an N+1 that nobody wrote, produced entirely by a default.
Two details in that log are worth noticing. There are four extra queries for eight books, because the eight books share four authors and the persistence context returns the same object for a row it has already loaded — the first-level cache, which the next lesson is about. And this happens on a @ManyToOne, the relationship people assume is cheap because it is "just one row".
Cascade is about lifecycle, not convenience
cascade says which operations travel along a relationship. The tempting one is CascadeType.ALL, and it is the one that removes data you did not mean to remove.
| Cascade | Travels |
|---|---|
PERSIST | saving the parent saves new children |
MERGE | merging the parent merges children |
REMOVE | deleting the parent deletes the children |
ALL | all of them, including REMOVE |
The question that decides it is not "is it convenient". It is can this child exist without this parent?
An OrderLine cannot exist without its Order — it is part of it, and deleting the order should delete the lines. CascadeType.ALL is right. A Book can exist without this Author in any system where books have several authors, or where deleting an author should not shred the catalogue. REMOVE there is a data-loss bug waiting for a routine cleanup job.
orphanRemoval = true is the stronger version and is often what people actually want: remove a child from the collection and it is deleted, not merely unlinked. Use it for true parts, never for associations.
Auditing: who and when, for free
Every table wants created_at, updated_at, and usually created_by and updated_by, and every hand-written version of them has one entity that forgets to set updatedAt on the second save. Spring Data JPA writes them for you:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "currentUser")
class AuditingConfig {
@Bean AuditorAware<String> currentUser() { return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()).map(Authentication::getName); }
}
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
abstract class Auditable {
@CreatedDate @Column(updatable = false) Instant createdAt;
@LastModifiedDate Instant updatedAt;
@CreatedBy @Column(updatable = false) String createdBy;
@LastModifiedBy String updatedBy;
}The listener fills the four fields on persist and on every flush that found the entity dirty, from the JVM's clock and the AuditorAware bean, so the values are consistent across the application and absent from every constructor. Two limits to know: a bulk @Modifying update bypasses the listener (it bypasses the persistence context, as the queries lesson says), so updated_at on those rows is yours to set in the statement; and this is who and when, not what — a history of changed values is an audit table written by the same transaction, or Hibernate Envers, or the event-sourcing decision the distributed-data course weighs.
What @Entity requires of you
Small, unglamorous rules, each of which produces a confusing failure when broken:
- A no-argument constructor, at least
protected. Hibernate instantiates entities reflectively, and a proxy subclass needs to call it. Make itprotectedrather thanpublicso your own code cannot build a half-built entity. - Not
final, and nofinalmethods on a lazily-loaded entity. Hibernate's proxy is a generated subclass; it cannot extend afinalclass or override afinalgetter — and the failure is a lazy field that silently stays null rather than an error. - A surrogate primary key. A natural key looks tidy until the business changes it, and a business does change an email address.
@Column(nullable = false)is not validation. It shapes the generated DDL and nothing else. If you use migrations — and the last lesson in this course argues you must — that annotation documents intent while the migration file decides reality. Validate with Bean Validation at the boundary instead.
Under the hood: cascade is an event listener, and orphanRemoval is a different mechanism entirely
The cascade table earlier in this lesson reads like configuration — tick the operations you want to travel — but each CascadeType maps to a real code path: when you call em.persist(parent), Hibernate fires a PersistEvent, and the default PersistEventListener walks every relationship on the entity looking for one that declares CascadeType.PERSIST (or ALL), then recursively calls the same persist logic on whatever it finds there. The same thing happens for merge, remove, refresh, and detach — each has its own event and its own listener, and each listener's cascade-walking logic only fires for relationships whose cascade attribute lists that specific operation. This is why cascade is precise rather than all-or-nothing in practice: CascadeType.PERSIST without REMOVE genuinely means "saving the parent saves new children" and nothing more — deleting the parent leaves the children exactly where they were, still pointing at a parent that no longer exists (which, without a NOT NULL foreign key, is a silent orphan; with one, a constraint violation at flush).
orphanRemoval = true is not a CascadeType at all, and that distinction is the point of this section: it is a separate element of @OneToMany and @OneToOne in the JPA specification itself (not a Hibernate extension), checked at a completely different moment. Cascade only ever runs in response to an explicit operation — someone called remove() on the parent. orphanRemoval runs during dirty checking, the same flush-time comparison the previous lesson's snapshot mechanism performs: Hibernate compares the collection's current contents against the snapshot it took when the collection was loaded, and if an element that was present in the snapshot is missing now, it schedules a DELETE for that element — whether or not the parent itself was touched at all.
Author a = em.find(Author.class, 1L);
a.getBooks().remove(0); // no em.remove() call anywhere, on the author or the book
em.getTransaction().commit();With plain CascadeType.REMOVE and no orphanRemoval, that code does nothing to the removed book's row — removing an element from a List is not calling remove() on the parent, so the REMOVE cascade's listener never fires, and the book still exists with its foreign key intact (or now dangling, if the in-memory link was also cleared). With orphanRemoval = true, the exact same code deletes the book's row at flush, because the collection comparison — not a cascade listener — is what triggered it. That is the real difference the cascade table's plain language ("deleting the parent deletes the children") does not capture: CascadeType.REMOVE answers "what happens when the parent is deleted", and orphanRemoval answers a different question entirely — "what happens when a child is unlinked from the parent's collection, whether or not the parent is touched."
Under the hood: why the generated-id trap in this lesson's equals/hashCode is not really about ids at all
This lesson's earlier section already shows the id-based equals/hashCode breaking once persist assigns an id — the object moves buckets between "before persist" and "after persist" because its hash code changed while it sat in the HashSet. It is worth being precise about why using all fields instead is not a safer alternative, because it looks like it should be: more fields means a more "accurate" notion of equality, surely.
It fails for the identical structural reason, just triggered more often. A HashSet/HashMap bucket is chosen once, at insertion, from whatever hashCode() returns at that moment — and nothing re-buckets an entry when a field it hashed on changes later, because nothing is watching the collection for that. An id-based hash changes exactly once (at persist) and only when the id is null beforehand, which is a narrow, specific trigger. An all-fields hash changes on every managed-entity mutation that touches a hashed field — renaming a Tag, changing an Order's status, anything the previous lesson's dirty checking is designed to notice and write — which is far more surface area for exactly the same silent-miss bug, not less. The generated-id case is the version of this bug that is guaranteed to happen to every entity exactly once; the all-fields case is the version that happens to any entity, any time a hashed field is later changed while it is sitting in a Set.
Try it yourself
Predict what happens with plain objects, no JPA involved
The HashSet/id-mutation problem in this lesson is a hashCode contract violation, not a JPA-specific mechanism — JPA is just a very common way to trigger it, because persist() assigning an id is exactly "a field the hash code depends on changing after insertion." The snippet below reproduces the identical failure with two plain classes that mimic the pattern — no @Entity, no framework, nothing but Object's hash contract — to make it concrete which field-change causes the miss and which does not.
class WidgetAllFields {
String name;
WidgetAllFields(String name) { this.name = name; }
@Override public boolean equals(Object o) {
return o instanceof WidgetAllFields w && w.name.equals(name);
}
@Override public int hashCode() { return name.hashCode(); }
}
class WidgetIdOnly {
final int id;
String name;
WidgetIdOnly(int id, String name) { this.id = id; this.name = name; }
@Override public boolean equals(Object o) {
return o instanceof WidgetIdOnly w && w.id == id;
}
@Override public int hashCode() { return id; }
}
java.util.Set<WidgetAllFields> allFieldsSet = new java.util.HashSet<>();
WidgetAllFields a = new WidgetAllFields("draft");
allFieldsSet.add(a);
a.name = "renamed";
System.out.println("findByAllFields after rename: " + (allFieldsSet.contains(a) ? "found" : "MISSING"));
java.util.Set<WidgetIdOnly> idOnlySet = new java.util.HashSet<>();
WidgetIdOnly b = new WidgetIdOnly(1, "draft");
idOnlySet.add(b);
b.name = "renamed";
System.out.println("findByIdOnly after rename: " + (idOnlySet.contains(b) ? "found" : "MISSING"));Both objects are renamed the same way, and both are still the exact same reference sitting in their set. Why does one lookup succeed and the other fail?
Only the hash-affecting field decides the bucket
WidgetAllFields.hashCode() is derived from name, so renaming it changes which bucket contains() computes on the second call — the object never moved, but the lookup now checks a different bucket than the one it is actually sitting in, exactly the mechanism the low-level-design course's equivalent example demonstrates. WidgetIdOnly.hashCode() is derived only from id, which this code never changes, so every contains() call computes the same bucket regardless of what name currently holds, and the lookup keeps finding it. This is the whole argument for basing a JPA entity's equals/hashCode on its id rather than its other fields: the id is (after persist) the one field on the entity that mutation never touches, so it is the one field safe to hash on for the object's entire managed lifetime.
Misconceptions
- "
CascadeType.REMOVEandorphanRemoval = trueare two ways of writing the same rule." They answer different questions, triggered by different mechanisms:REMOVEcascade fires only when the parent itself is explicitly removed, via Hibernate's remove-event listener walking the relationship graph;orphanRemovalfires during dirty checking's collection comparison whenever an element disappears from the collection, whether or not the parent was touched. A composition relationship usually wants both, but they are not redundant —orphanRemovalwithoutREMOVEstill deletes an unlinked child even if the parent is never deleted at all. - "Basing equals/hashCode on more fields makes entity equality more correct." For a
HashSet/HashMapspecifically, it makes the hash-code-changes-after-insertion bug more likely to trigger, not less — every additional hashed field is one more mutation that silently strands the object in the wrong bucket. An entity's identity for collection purposes is best served by the one field a JPA entity is guaranteed not to mutate after it is first assigned: the id (or a genuine, immutable business key).
Sources
- Hibernate ORM User Guide, "Persisting and cascading entity state transitions" — the event-listener mechanism behind each
CascadeType. - Hibernate ORM User Guide, "Bidirectional associations" and the
orphanRemovalsemantics as distinct from cascadeREMOVE. - Jakarta Persistence Specification (JSR 338 / Jakarta Persistence 3.x) § 3.2.3 and § 11.1.24 — the
CascadeTypeenum and theorphanRemovalelement of@OneToMany/@OneToOne. - Vlad Mihalcea, "The best way to map a
@OneToManyrelationship with JPA and Hibernate" — the orphan-removal-versus-cascade distinction and its collection-comparison mechanics.