Search code examples
spring-dataoptimistic-lockingspring-data-jdbc

Optimistic Locking in Spring Data JDBC


I noticed that Spring Data JDBC doesn't seem to implemented Optimistic Locking (something like a JPA's @Version annotation).

I was thinking on creating a @Modifying query which considers the version field and returns boolean to check manually if the update was successful or not. But I'm afraid this approach is limited to simple entities, not aggregates implying multiple tables.

What's the best way to implement optimistic locking for aggregates?


Solution

  • It depends on your situation. If you just have 7 aggregates of which 5 are single entity aggregates go for the @Modifying solution for the single aggregates and write custom methods for the other 2.

    If you have more aggregates consisting of more then one class consider properly implementing it and submitting a PR. The issue is already there: https://jira.spring.io/projects/DATAJDBC/issues/DATAJDBC-219

    The main code changes will be in SqlGenerator which would need to add a where clause for aggregate roots if they have a version attribute.

    If you are interested in doing a PR and need more assistance, please leave comment on the issue.