JPA Optimistic Locking With @Version

9,391 views
8,801 views

Published on

Published in: Business, Technology

JPA Optimistic Locking With @Version

  1. 1. JPA Optimistic Locking With @Version Albert Guo junyuo@gmail.com
  2. 2. Problem No Task Time 1 2 3 4 1 User A read row 2 2 User B read row 2 3 User A update row 2 4 User B update row 2 2 Two users try to update the same data, it may cause the later user will process out-of-date (stale) data. User B may assigned new values to row 2 based on out-of-date information.
  3. 3. Optimistic Locking • A common strategy for avoiding stale data is to implement optimistic locking, and store the optimistic lock values in the object. • When a user attempts to write a change, the application checks to ensure the data has not changed since the user read the data. 3
  4. 4. OptimisticVersion Locking • Use the @Version annotation to enable the JPA-managed optimistic locking by specifying the version field or property of an entity class that serves as its optimistic lock value (recommended). 4
  5. 5. DEMO – HOW TO ENABLE JPA OPTIMISTICVERSION LOCKING 5
  6. 6. Create a table with version column 6
  7. 7. Create entity 7 JPA provide automatic support of row versioning via the @Version annotation. When you have entity with @Version annotated field or property, optimistic locking will be enabled automatically. The version field or property type must either be a numeric type (such as Number, long, int, BigDecimal, and so on), or a java.sql.Timestamp. We recommend using a numeric type.
  8. 8. Save new entity 8
  9. 9. Save new entity – cont. 9 JPA will maintain version value automatically
  10. 10. Update entity 10
  11. 11. Update entity – cont. 11 JPA will maintain version value automatically. The version value will increment by 1, from 1 to 2.
  12. 12. DEMO – OPTIMISTIC LOCK EXCEPTION 12
  13. 13. Scenario 13 No Task Time 1 2 3 4 1 User A read row 2 2 User B read row 2 3 User A update row 2 4 User B update row 2 Task #1 Task #2
  14. 14. Scenario – cont. 14 No Task Time 1 2 3 4 1 User A read row 2 2 User B read row 2 3 User A update row 2 4 User B update row 2 Task #3 Task #4
  15. 15. OriginalValue 15
  16. 16. Update entity 16 No Task Time 1 2 3 4 1 User A read row 2 2 User B read row 2 3 User A update row 2 4 User B update row 2 Task #1 Task #2
  17. 17. Update entity – cont. 17 No Task Time 1 2 3 4 1 User A read row 2 2 User B read row 2 3 User A update row 2 4 User B update row 2 Task #3 Task #4 Owing to user A had updated successfully, the version value had been update to 3. User B do update based on version value 2 (based on stale information), so JPA will throw OptimisticLockException.
  18. 18. Update entity – cont. 18 The color had been updated to GREY, and the version value had been updated incrementally from 2 to 3.

×