Video in progress
What does orphanRemoval = true do and how is it different from CascadeType.REMOVE?
orphanRemoval deletes a child from the database when it is removed from the parent's collection. CascadeType.REMOVE deletes the children only when the parent itself is deleted; taking one out of the collection has no effect on it.
📖 Answer
@OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true)
private List<CartItem> items = new ArrayList<>();
public void removeItem(CartItem item) {
items.remove(item);
item.setCart(null);
}
After cart.removeItem(item), the flush sends DELETE FROM cart_item WHERE id = ?. Without orphanRemoval, Hibernate would only try to set cart_id = NULL (and fail if the column is NOT NULL).
The difference in one table:
| Case | REMOVE |
orphanRemoval |
|---|---|---|
em.remove(cart) |
items are deleted | items are deleted |
cart.getItems().remove(item) |
not deleted | deleted |
One trap: don't replace the collection wholesale with a new one (cart.setItems(newList)). The collection wrapper that Hibernate tracks is lost, and you get "A collection with cascade=all-delete-orphan was no longer referenced". The right way is items.clear(); items.addAll(newList);.
Sign up to mark studied questions and save your progress.