Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does the @version works

 
Senthil Kumar
Ranch Hand
Posts: 264
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain what is the logic behind annotating an entity field as Version.
 
Benoît de Chateauvieux
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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.
 
Camilo Morales
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Hope this helps,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic