Video in progress
What do you do when the parent entity's version must be incremented even if only a child entity changed?
You read the parent with LockModeType.OPTIMISTIC_FORCE_INCREMENT or call em.lock(parent, ...): Hibernate increments the parent's @Version even if the parent itself didn't change. That way the whole aggregate is protected by a single version.
📖 Answer
The problem: Order has @Version, but the OrderLines don't. Two users add a line to the same order at the same time. Both only INSERT an OrderLine: the order row isn't touched, the version doesn't change, and the conflict goes unnoticed. The result: the order exceeds a limit (say, at most 10 lines or a total amount), because each one checked "there are 9 right now".
The fix is to force the parent's version to increment when the children change too:
@Transactional
public void addLine(Long orderId, LineDto dto) {
Order order = em.find(Order.class, orderId, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
if (order.getLines().size() >= 10) throw new LimitException();
order.addLine(new OrderLine(dto));
}
At commit Hibernate writes:
update orders set version = 8 where id = ? and version = 7
The second transaction expects version = 7 too, updates 0 rows, and gets OptimisticLockException.
In Spring Data: @Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT) on the repository method.
There's also PESSIMISTIC_FORCE_INCREMENT: it locks the row on read and increments the version right away. It's useful when conflicts are frequent.
This is how the DDD idea of "the aggregate root is the consistency boundary" looks in Hibernate. If the inner objects are changed only through the root, and the root increments its version every time, the invariants are protected across the whole aggregate.
Sign up to mark studied questions and save your progress.