Can someone explain what is the logic behind annotating an entity field as Version.
when you really want something, all the universe always conspires in your favour.<br /> <br />SCJP1.5-77%<br />SCWCD-89%
Benoît de Chateauvieux
Joined: Aug 10, 2007
@Version is the implementation of the Optimistic Locking Design Pattern. It's an alternative to the traditional DB locking.
Whenever your entity is updated, the version column is incremented. When a transaction begins the commit process, the entity manager looks to see if the version it has in memory match the version in database.
If it doesn't, it means that another thread did an update on this row. In this case, the entity manager throws an exception and the transaction is rolled back.
SCJP5 | SCBCD5 | SCEA5 Part 1
Joined: Jul 14, 2007
The @Version field gives the persistent provider, in the case of the Optimistic locking technique, the opportunity to check if an entity have been changed since it was first retrieved from the DB. @Version field is very related with the MERGE operation. If you find/getReference an entity and then detached it ( in order to send it through the network for example), any change made to that serialized instance of the entity won't have effect in the underliyng datastore, but if then you receive back your entity instance with some updated fields (@Id and @ Version fields should not be updated by any other role different to the persistence provider) and you want to persist it with the changes made to the serialized instance, you must use the MERGE operation. Before that, the persistence provider must be sure that nobody updated any field of that entity since it was first retrieved, and here is when it checks the @Version field and if it is the same of the serialized object ,,, it ok to merge the entity ,,, otherwise, an optimistic locking exception is thrown.