Implementing Optimistic lock using Hibernate and Spring

我怕爱的太早我们不能终老 提交于 2019-11-27 20:19:07

JPA/Hibernate Optmistic locking works by using some field to store the last modified version (e.g. timestamp, long) and then comparing the version of the entity in the session with the entity in the database to see if the change can be saved.

For this to work you need to have a field in your entity annotated with @Version.

See below for an example.

http://www.javacodegeeks.com/2012/11/jpahibernate-version-based-optimistic-concurrency-control.html

For this to work in a web application requires further thought however as if two people load the same entity for editing and then some time later submit their edits they will likely both succeed as, unless you are using some kind of long running session, the entity being edited will be reloaded from the database on form submit, populated and saved.

e.g. Entity at Revision 1

  • user 1 loads for edit: revision at 1
  • user 2 loads for edit: revision at 1
  • user 2 submits form: entity (at r1) loaded, fields are bound, entity is saved: revision is 2.
  • user 1 submits form: entity (at r2) is loaded, fields are bound, entity is saved: revision is 3.

So for this to work you could look at submitting a hidden field with the form which stores the entity revision at the time it was loaded. So, on the last step above, when user 1 submits, the revision field will be set back to 1 and the update will fail because the record in the DB as at r2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!