Video in progress
What happens if you replace a collection with `orphanRemoval = true` wholesale using `setItems(newList)`?
Hibernate tracks the collection through its own PersistentBag/PersistentSet wrapper. If you replace it with a new ArrayList, the flush fails with "A collection with cascade=all-delete-orphan was no longer referenced". The right way is to clear() the existing collection and add the elements again.
📖 Answer
Code you see a lot is updating an entity from a DTO:
@Transactional
public void update(Long id, OrderDto dto) {
Order order = repo.findById(id).orElseThrow();
order.setItems(dto.items().stream().map(this::toItem).toList()); // the mistake is here
}
The loaded order.items is not a plain List but Hibernate's PersistentBag. It knows which elements were removed, and orphanRemoval relies on that information. When you replace the reference with a new list, the old wrapper is left "ownerless" and Hibernate can't tell which rows to delete, so it throws an exception. On top of that, toList() returns an immutable list, so a later add() would fail too.
The right version:
public void replaceItems(List<OrderItem> newItems) {
items.clear(); // the old elements become orphans -> DELETE
newItems.forEach(this::addItem); // addItem links both sides
}
It's even better to remove the setter altogether: only methods inside the entity should change the collection. Then this mistake disappears at compile time.
One note: clear() plus re-adding deletes all the old rows and writes the new ones. If there are a lot of elements, it's more efficient to compare by id and apply only the difference.
Sign up to mark studied questions and save your progress.