In JPA you can annotate a field of an entity with @Version to specify that property as its optimistic lock value.
But the above documentation does not say when the version number is validated and updated (increased).
The short answer is: at commit time!
I came across this because I was having trouble passing on the updated version number back to the caller, after a merge() operation.
Example and the solution
- The JPA implementation (in this case Hibernate) can do some caching, deferring the actual database access to a later moment, causing the changes to not hit the database yet.
- Not hitting the database also doesn't cause the @Version to be "triggered" (it seems).
- So the version is still at its old value!