• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How does the @version works

 
Ranch Hand
Posts: 264
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone explain what is the logic behind annotating an entity field as Version.
 
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic