Video in progress

Strong Middle 🌱 Spring

What mistakes do you run into when working with cascade and orphanRemoval on @OneToMany?

The most common: putting CascadeType.ALL on the @ManyToOne side and deleting a shared object; replacing the collection with setItems(newList) and hitting an orphanRemoval error; filling in only one side of the relationship and leaving the foreign key null.

📖 Answer

The right template for a parent-child (aggregate) relationship:

@Entity
class Order {
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private final List<OrderLine> lines = new ArrayList<>();

    public void addLine(OrderLine l) {
        lines.add(l);
        l.setOrder(this);      // both sides
    }

    public void removeLine(OrderLine l) {
        lines.remove(l);
        l.setOrder(null);      // orphanRemoval issues the DELETE
    }
}

The mistakes you run into:

  1. Replacing the collection. With order.setLines(new ArrayList<>(dto.lines())), the collection Hibernate is tracking is lost and you get the error A collection with cascade="all-delete-orphan" was no longer referenced. Do clear() + addAll() on the existing list, or compute the difference and add/remove.
  2. Only one side. If you do lines.add(l) and forget l.setOrder(this), because of mappedBy the owner is the OrderLine side, so the foreign key is saved as null or you get a NOT NULL error.
  3. Cascading to the wrong side. If cascade = REMOVE is put on OrderLine.product, deleting a line tries to delete the product too. Cascade only goes parent → child, and only where the child can't live without the parent.
  4. A shared child. orphanRemoval may delete a child even when it's being moved to another parent, so it's unsuitable for moving.
  5. A large collection. Deleting a parent with 50 thousand children using cascade = REMOVE loads each one and issues a separate DELETE. In that case a bulk query or ON DELETE CASCADE in the database is better.

The rule: use cascade and orphanRemoval only inside a real aggregate (an order and its lines), not between entities that live independently.