简体   繁体   中英

Optimistic Locking in Hibernate does not change the value of the version-column in the table

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 (eg 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.

I had a similar issue, and mine was because the data was not flushed to the database prior to the second DML.

To test, i changed my repository and extends JpaRepository instead of extends CrudRepository . Then instead of doing save , i did saveAndFlush . My version field was updated as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM