To implement optimistic locking in Spring Boot project, I added a field with the @Version annotation:
package com.example.my_api.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "clients")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Client {
// ...
@Version
private Integer version;
// ...
}
Then i added a version-column in the corresponding table, using Liqubase-migration:
And now, I'm testing with Postman. First I create a new client with a POST-request, then I update its data (name, age) with a PUT-request. If I understand correctly, when we update the entity, it should automatically increase the value of the version-field by 1. But in my case this does not happen:
The value is 0 and it is not incremented. Can you help me? What i do wrong?
Accepted answer from this similar question: How to increase a version field on save in Hibernate regardless if dirty or not?
You can use Hibernate interceptors to update the version number of the master record when you identify that detail has changed.
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html
One limitation is that this solution is specific to Hibernate. JPA also allows event-driven logic using annotations (e.g. PostPersist, PostUpdate, etc...) but these methods don't give you access to the underlying session (and, more importantly, the documentation cautions you from using these methods to modify session data). I've typically used interceptors to perform auditing, but they could easily be extended to update a version number when a record is altered.