@Version乐观锁配置mybatis-plus使用(version)

1:首先在实体类的属性注解上使用@Version

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.util.Date;

/**
 * @Description: 访客数据
 * @Author: xqf
 * @Date:   2023-07-27
 * @Version: V1.0
 */
@Data
@TableName("sys_visitant_data")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="sys_visitant_data对象", description="访客数据")
public class SysVisitantData {

	/**id*/
	@TableId(type = IdType.ASSIGN_ID)
    @ApiModelProperty(value = "id")
	private String id;
	/**访客openId*/
	@Excel(name = "访客openId", width = 15)
	@ApiModelProperty(value = "访客openId")
	private String visitantOpenId;
	@Version
	private Long version;
}

2:在数据库表中添加version字段,注意实体类使用是long和int类型(和默认值为0)

@Version乐观锁配置mybatis-plus使用(version)_第1张图片

3:在mybatis-plus拦截器中添加OptimisticLockerInnerInterceptor()乐观锁拦截器

@Configuration
@MapperScan(value={"org.demo.modules.**.mapper*"})
public class MybatisConfig {
@Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor= new MybatisPlusInterceptor();
        //添加分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        //添加乐观锁拦截器
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

4:demo(version字段版本会自动每次加一操作)

@PostMapping("/apply2")
    public Result<?> apply2() {
        SysVisitantData visitantData = sysVisitantDataService.getById("1724065295435689986");
        Integer visitantNumber = visitantData.getVisitantNumber();
        System.out.println("开始#2:" + visitantNumber);
        visitantData.setVisitantNumber(visitantNumber + 5);
        boolean flag = sysVisitantDataService.updateById(visitantData);
        if (!flag){
            throw new JeecgBootException("2保存失败");
        }
        System.out.println("更新#2:" + visitantData.getVisitantNumber());
        return Result.OK();
    }

你可能感兴趣的:(mybatis,java,开发语言)