1 引言
乐观锁的主要作用在于提高系统的并发性能和减少锁冲突,同时保证数据的一致性。其原理简单来说就是,在修改数据的时候,判断数据是否被其他人改过,如果已被其他人改过,则修改失败。
2 代码
在SpringBoot 3.x+Mybatis Plus多数据源极简配置中的项目基础上更新代码,下面列出需要更新的代码。

2.1 org/example/mapper/InventoryMapperMaster.java
package org.example.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.entity.Inventory;
@DS("master")
public interface InventoryMapperMaster extends BaseMapper<Inventory> {
}
2.2 org/example/entity/Inventory.java
@Version就是乐观锁字段,用于判断数据是否被修改过。
package org.example.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;
/*
* 库存
* */
@TableName("t_inventory")
public class Inventory {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer quantity;
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this

最低0.47元/天 解锁文章
621

被折叠的 条评论
为什么被折叠?



