BBackend CourseLeroy Labs
0/0
Search the course

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.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2SperoTek (in dev)

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 UPDATE for whatever changed. You never have to call save() 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.
  • mappedBy marks the inverse side. In bidirectional relationships you must set both sides in Java, which is usually done with a helper method like addRoom(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

Spring-Boot-Storeentities/User.java · Profile.java · Cart.java · Order.java

Store 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.

Hostel-Web-Appmodule/booking/model/Booking.java

All @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(...).

Report-Manager-2module/reportunit/domain/ReportUnit.java · user/domain/User.java

A self-referencing tree with @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) Set<ReportUnit> subunits, plus User ↔ Role ↔ Permission as two lazy @ManyToMany join tables.

SperoTek (in dev)ledger/domain/JournalEntry.java

SperoTek 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
  • equals/hashCode on entities. Base them on the id, and handle a null id for transient entities (see the modern Java lesson).
  • FetchType defaults. @ManyToOne and @OneToOne are EAGER by default, so always set LAZY. @OneToMany and @ManyToMany are lazy by default.
  • Set vs List. A Hibernate List without an order column is a “bag”, and fetching two bags at once throws MultipleBagFetchException.
  • Flush modes. Hibernate flushes before queries that might read pending changes.
  • save() vs saveAndFlush(), and persist vs merge.

Check yourself

1. Which side of a bidirectional @OneToMany/@ManyToOne writes the FK?
2. You remove an Address from user.getAddresses(). With orphanRemoval=true…
3. Default fetch type of @ManyToOne?