mybatis-plus使用乐观锁

1.config配置文件

package com.mods.browser.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan({"com.mods.browser.mapper", "com.mods.mbg.mapper", "*.mapper"})
public class MybatisConfig {
    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    //乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

2. 表字段

  • 主要是添加version这个字段,用于乐观锁
类型 长度
id int 32
name varchar 255
del_status char 1
create_time datetime 0
update_time datetime 0
version int 32

3. 实体类及注解

package com.mods.mbg.model;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import java.util.Date;

import com.baomidou.mybatisplus.annotation.Version;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@TableName("t_test")
@ApiModel(value="Test对象", description="")
public class Test implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String name;
    private String delStatus;
    private Date createTime;
    private Date updateTime;
    @Version
    private Integer version;
}

4. 测试

更新的业务:先查询,后修改。

在使用更新操作之后,version会增加。

上一篇:SpringSecurity系列之查询数据库认证


下一篇:Springboot项目异常记录