Optimistic locking not throwing exception when manually setting version field

前端 未结 4 490
太阳男子
太阳男子 2020-12-08 17:03

I have a Spring Boot 1.3.M1 web application using Spring Data JPA. For optimistic locking, I am doing the following:

  1. Annotate the version column in the entity:
4条回答
  •  难免孤独
    2020-12-08 17:30

    Part of the @AdrianShum answer is correct.

    The version comparing behavior follows basically this steps:

    1. Retrieve the versioned entity with its version number, lets called V1.
    2. Suppose you modify some entity's property, then Hibernate increments the version number to V2 "in memory". It doesn't touch the database.
    3. You commit the changes or they are automatically commited by the environment, then Hibernate will try to update the entity including its version number with V2 value. The update query generated by Hibernate will modify the registry of the entity only if it match the ID and previous version number (V1).
    4. After the entity registry is successfully modified, the entity takes V2 as its actual version value.

    Now suppose that between steps 1 and 3 the entity was modified by another transaction so its version number at step 3 isn't V1. Then as the version number are different the update query won't modify any registry, hibernate realize that and throw the exception.

    You can simply test this behavior and check that the exception is thrown altering the version number directly on your database between steps 1 and 3.

    Edit. Don't know which JPA persistence provider are you using with Spring Data JPA but for more details about optimistic locking with JPA+Hibernate I suggest you to read chapter 10, section Controlling concurrent access, of the book Java Persistence with Hibernate (Hibernate in Action)

提交回复
热议问题