Cascading and orphan removal
Let operations flow from parent to child without deleting rows you meant to keep.
Open this lesson in the learning hubKey points
- Cascade means: whatever I do to the parent, do to these children. The options are
PERSIST,MERGE,REMOVE,REFRESH,DETACH. CascadeType.ALLis right when a child cannot exist alone. An order line without its order is nonsense.orphanRemoval = truedeletes a child as soon as you remove it from the collection. Cascade REMOVE only reacts to deleting the parent.- Never cascade REMOVE from a
@ManyToOne. Deleting one book would delete its author, and every other book with it. - Orphan removal deletes row by row. For a bulk clean-up write a delete query instead.
Example
@Entity
public class Order {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "order",
cascade = CascadeType.ALL, // persist/merge/remove flow down
orphanRemoval = true) // dropped from the list = DELETE
private List<OrderLine> lines = new ArrayList<>();
public void addLine(OrderLine line) {
lines.add(line);
line.setOrder(this);
}
public void removeLine(OrderLine line) {
lines.remove(line); // orphanRemoval turns this into a DELETE
line.setOrder(null);
}
}
Cascade along real ownership only: parent to child, never child to parent.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Hibernate course, and every lesson in it is listed on the Hibernate contents page.