I have a web application created using Tapestry5 (java webframework) and Hibernate. Now I'm trying to add an optimistic lock. So I added a version attribute and optimistic locks, so it was easy and fast.
But since my web application works with the session-per-request pattern, I'm not sure which is the best way to use this optimistic lock.
What's happening:
UserA opens a page with a form that is loaded with values ββfrom entityA (version 1).
UserB opens a page with a form that is loaded with values ββfrom entityA (version 1).
UserA changes some values ββand submits the form. -> A new request receives an entityA object (version 1) and commits the changes (entityA is now version 2)
UserB modifies some values ββand submits the form. -> A new request receives an entityA object (version 2 ) and commits the changes (entityA is now version 3)
What is going to happen
UserB changes should not be made. But because of the session-per-request template, the time window in which an optimistic Hibernate lock error can occur is reduced to the time interval only from a new request after sending for commit, which is not the desired result.
Possible solutions
After some research, I found the following:
- Add a hidden field to the entity version form
I could use this value to set the version of the object before committing, but the Hibernate documentation does not recommend setting this value. It also works only if the object is disconnected and reconnected, because otherwise the value set manually will be ignored using Hibernate.
Secondly, I can use this version value for manual verification if the version when the form was rendered is the same as the version of the object loaded in the submit request. Then, if necessary, throw an optimistic Exception.
- Put a separate object in HttpSession, so I donβt need to upload it again in submit
Conclusion
These methods work, but do not seem to me very practical and are easily mistaken. Therefore, I wonder how other people implement this problem.