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

原文地址:https://blog.csdn.net/qq_74312711/article/details/134748237

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_38982.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注