Hibernate StaleObjectStateException during Concurrent Updates

后端 未结 1 537
时光说笑
时光说笑 2020-12-29 00:37

I am using Hibernate 3.5.2 and Spring Core 3.0.1 in a Java J2EE Web Application. I am getting a StaleObjectStateExcpetion when separate users are updating the same record co

相关标签:
1条回答
  • 2020-12-29 01:22

    Here is how optimistic locking works:

    1. User1 starts to edit recordA - recordA is loaded from the database with version V
    2. User2 starts to edit recordA - recordA is loaded from the database with version V - exactly the same as above
    3. User1 saves recordA - recordA is saved but Hibernate transparently adds:

      UPDATE
      ...
      SET V = V + 1
      WHERE version = V
      

      At this point Hibernate verifies whether the number of modified records returned from the database is exactly 1. If the query modified 0 records it means that the WHERE version = V clause was not met. In this case everything went fine and the version was set to V + 1 (important!)

    4. User2 saves recordA - Hibernate does exactly the same thing, still having the old V version number in memory. Unfortunately in this case the WHERE version = V condition is not met since version is now V + 1. The query returns 0 modified records which makes Hibernate believe (correctly) that the record was modified in the meantime. This is what the exception says.

    So what can you do about it? Simply catch the exception and:

    1. Repeat the whole transaction, but reload the entity (with new version V + 1) so that after updating you won't loose the last change

    2. Or inform the user that the object was modified in the meantime so she can inspect the new version.

    Both solutions are fine depending on your use case.

    0 讨论(0)
提交回复
热议问题