StackOverflow and the Hibernate forum are gold mines. Yesterday, I bumped on the following question on our forum:
Usually, the rationale behind clustering objects together is to form a transactional boundary inside which business invariants are protected. I’ve noticed that with the OPTIMISTIC locking mode changes to a child entity will not cause a version increment on the root. This behavior makes it quite useless to cluster objects together in the first place.
Is there a way to configure Hibernate so that any changes to an object cluster will cause the root object’s version to increment? I’ve read about OPTIMISTIC_FORCE_INCREMENT but I think this does increment the version regardless of if entities were changed or not. Since reads shouldn’t be conflicting with other reads in most scenarios, this doesn’t seem so useful either.
I could always increment the version inside every mutating behavior of the root, but that is quite error-prone. I’ve also thought of perhaps using AOP to do this, but before looking into it, I wanted to know if there were any easy way to do that. If there were a way to check if an object graph is dirty, then it would make it quite easy to implement as well.
What a brilliant question! This post is going to demonstrate how easy you can implement such a requirement when using Hibernate.