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;
@Data
@TableName("sys_visitant_data")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="sys_visitant_data对象", description="访客数据")
public class SysVisitantData {@TableId(type = IdType.ASSIGN_ID)@ApiModelProperty(value = "id")private String id;@Excel(name = "访客openId", width = 15)@ApiModelProperty(value = "访客openId")private String visitantOpenId;@Versionprivate Long version;
}
2:在数据库表中添加version字段,注意实体类使用是long和int类型(和默认值为0)
3:在mybatis-plus拦截器中添加OptimisticLockerInnerInterceptor()乐观锁拦截器
@Configuration
@MapperScan(value={"org.demo.modules.**.mapper*"})
public class MybatisConfig {
@Beanpublic 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();}