JPA / Hibernate Optimistic locking works by using some field to store the last modified version (for example, timestamp, long), and then compares the version of the object in the session with the entity in the database to see if the change can be saved.
To do this, you need to have a field in the object annotated with @Version.
The following is an example.
http://www.javacodegeeks.com/2012/11/jpahibernate-version-based-optimistic-concurrency-control.html
To do this, working in a web application requires further thought, as if two people uploaded the same object for editing, and then after a while sent their changes, they are likely to be successful if you do not use some kind of long session, the edited object will be reloaded from the database in the submit form, filled and saved.
eg. Object in edition 1
- user 1 download for editing: version 1
- user 2 downloads for editing: revision 1
- User 2 submits the form: the object (in r1) is loaded, the fields are attached, the entity is saved: version is 2.
- User 1 submits the form: the object (in r2) is loaded, the fields are attached, the object is saved: version 3.
So, for this you can see how to send a hidden field with the form in which the revision of the object is stored at the time of its loading. Thus, in the last step above, when user 1 sends, the revision field will be set to 1, and the update will fail because the database entry is like r2.
source share