Mybatis-Plus实现乐观锁
MybatisPlusConfig
添加乐观锁插件
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 添加乐观锁插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
数据库表
关键字段version
create table if not exists tb_student
(
id bigint auto_increment comment '主键id'
primary key,
name varchar(8) not null comment '姓名',
gender int not null comment '性别;1代表男,2代表女',
age int not null comment '年龄',
version int default 1 not null comment '乐观锁',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '更新时间',
constraint id
unique (id)
)
comment '学生表';
insert into tb_student (id, name, gender, age, version, create_time, update_time)
values (null, '艾伦', 1, 15, 1, now(), now());
StudentEntity
使用@Version注解
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_student")
public class StudentEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField(value = "name")
private String name;
@TableField(value = "gender")
private Integer gender;
@TableField(value = "age")
private Integer age;
@Version
private Integer version;
@TableField(value = "create_time")
private LocalDateTime createTime;
@TableField(value = "update_time")
private LocalDateTime updateTime;
}
测试
@Autowired
private StudentMapper studentMapper;
@Test
public void test() {
StudentEntity studentEntity = new StudentEntity();
studentEntity.setId(1L);
studentEntity.setAge(16);
studentEntity.setVersion(1);
studentEntity.setUpdateTime(LocalDateTime.now());
studentMapper.updateById(studentEntity);
}
查看SQL
==> Preparing: UPDATE tb_student SET age=?, version=?, update_time=? WHERE id=? AND version=?
==> Parameters: 16(Integer), 2(Integer), 2023-12-02T10:25:33.361643700(LocalDateTime), 1(Long), 1(Integer)
<== Updates: 1