JPA entities & relationships, including cascade, orphanRemoval and owning sides
How Hibernate maps objects to tables. @ManyToOne, @OneToMany(mappedBy), @ManyToMany, @MapsId, cascade types, orphanRemoval, the persistence context, and why SperoTek mostly avoids associations.
The concept
JPA is the specification and Hibernate is the implementation. It maps classes to tables and object references to foreign keys.
The persistence context (first-level cache)
Inside a transaction, Hibernate keeps every entity it loaded in a persistence context. That has three effects:
- Loading the same id twice returns the same object without a second query.
- Dirty checking. At flush or commit, Hibernate compares each entity to its snapshot and issues an
UPDATEfor whatever changed. You never have to callsave()on a managed entity. - Entity states: transient (new), managed, detached (after the transaction closes), removed.
@Transactional
public void rename(UUID id, String name) {
Hostel h = repo.findById(id).orElseThrow();
h.setName(name); // no save() needed: dirty checking issues the UPDATE at commit
}
Relationships
@Entity class Room {
@ManyToOne(fetch = FetchType.LAZY) // owning side: holds the FK column
@JoinColumn(name = "hostel_id", nullable = false)
private Hostel hostel;
}
@Entity class Hostel {
@OneToMany(mappedBy = "hostel") // inverse side: just mirrors
private List<Room> rooms = new ArrayList<>();
}
- The owning side is the side with the FK, which is always the
@ManyToOne. Only changes on the owning side are written to the DB. mappedBymarks the inverse side. In bidirectional relationships you must set both sides in Java, which is usually done with a helper method likeaddRoom(room).
Cascade and orphanRemoval
| Option | Meaning |
|---|---|
cascade = PERSIST |
Saving the parent saves new children |
cascade = MERGE |
Merging the parent merges the children |
cascade = REMOVE |
Deleting the parent deletes the children |
cascade = ALL |
All of the above, plus REFRESH and DETACH |
orphanRemoval = true |
Removing a child from the collection deletes its row |
Only cascade from a true aggregate root to the parts it owns (Order → OrderItems). Never cascade toward shared entities (OrderItem → Product).
In your projects
entities/User.java · Profile.java · Cart.java · Order.javaStore shows almost every mapping type:
// User
@OneToMany(mappedBy = "user", cascade = {PERSIST, REMOVE}, orphanRemoval = true)
private List<Address> addresses;
@OneToOne(mappedBy = "user") private Profile profile;
@ManyToMany @JoinTable(name = "wishlist", ...) private Set<Product> wishlist;
// Profile: shared primary key
@OneToOne(fetch = LAZY) @JoinColumn(name = "id") @MapsId private User user;
// Cart: the aggregate root owns its items
@OneToMany(mappedBy = "cart", cascade = MERGE, orphanRemoval = true, fetch = EAGER)
private Set<CartItem> items;The entities hold domain logic too: Cart.addItem/removeItem/getTotalPrice/clear, Order.fromCart(cart, customer) and Order.isPlacedBy(user). That is a rich domain model rather than an anemic one.
module/booking/model/Booking.javaAll @ManyToOne(fetch = LAZY) with DB-level @OnDelete. Instead of public constructors and setters, it uses static factories that enforce valid creation: Booking.createBooking(request, student, room), Booking.createWaitlistDraft(...) and Room.createRoom(...).
module/reportunit/domain/ReportUnit.java · user/domain/User.javaA self-referencing tree with @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) Set<ReportUnit> subunits, plus User ↔ Role ↔ Permission as two lazy @ManyToMany join tables.
ledger/domain/JournalEntry.javaSperoTek uses few associations. JournalEntry has a @OneToMany to its lines (with cascade and @OrderBy) because lines are part of the entry aggregate. Most other references are plain UUID columns (periodId, reverses, companyId). Cross-module references become plain ids, so modules don’t load each other’s entities, which keeps the Modulith boundaries intact.
Alternatives
| Tool | When |
|---|---|
| JPA/Hibernate (yours) | Rich domain models, CRUD-heavy apps |
| Spring Data JDBC | Simpler: no lazy loading, no dirty checking, aggregates only |
| jOOQ / JdbcClient | SQL-first; SperoTek uses JdbcClient for reports and numbering |
| MyBatis | Hand-written SQL mapped to objects |
Related concepts you must know
equals/hashCodeon entities. Base them on the id, and handle a null id for transient entities (see the modern Java lesson).FetchTypedefaults.@ManyToOneand@OneToOneare EAGER by default, so always setLAZY.@OneToManyand@ManyToManyare lazy by default.SetvsList. A HibernateListwithout an order column is a “bag”, and fetching two bags at once throwsMultipleBagFetchException.- Flush modes. Hibernate flushes before queries that might read pending changes.
save()vssaveAndFlush(), andpersistvsmerge.