Video in progress
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:
- Replacing the collection. With
order.setLines(new ArrayList<>(dto.lines())), the collection Hibernate is tracking is lost and you get the errorA collection with cascade="all-delete-orphan" was no longer referenced. Doclear()+addAll()on the existing list, or compute the difference and add/remove. - Only one side. If you do
lines.add(l)and forgetl.setOrder(this), because ofmappedBythe owner is theOrderLineside, so the foreign key is saved asnullor you get a NOT NULL error. - Cascading to the wrong side. If
cascade = REMOVEis put onOrderLine.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. - A shared child.
orphanRemovalmay delete a child even when it's being moved to another parent, so it's unsuitable for moving. - A large collection. Deleting a parent with 50 thousand children using
cascade = REMOVEloads each one and issues a separate DELETE. In that case a bulk query orON DELETE CASCADEin 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.
Sign up to mark studied questions and save your progress.