Mybatisplus----DML编程控制

乐观锁

(1)业务并发现象带来的问题:秒杀

执行:

1、在类对象中添加version属性,在数据库表中添加version字段(默认值为1)

package com.itheima.domain;


import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

@Data
//@TableName("tbl_user")
public class User {

//    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    @TableField(value = "pwd", select = false)
    private String password;
    private Integer age;
    private String tel;
    @TableField(exist = false)
    private Integer online;
    //逻辑删除字段,标记当前记录是否被删除
//    @TableLogic(value = "0", delval = "1")
    private Integer deleted;

    @Version
    private Integer version;


}

 

 

 2、创建config.MpConfig类,在类中创建乐观锁拦截器

package com.itheima.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MpConfig {
    @Bean
    public MybatisPlusInterceptor mpInterceptor(){
        //定义mp拦截器
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        //添加具体的拦截器(分页)
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        //添加乐观锁拦截器
        mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return mpInterceptor;
    }



}

3、测试

  @Test
    void testUpdate(){
        User user = userDao.selectById(3L);  //version=5

        User user2 = userDao.selectById(3L); //version=5

        user2.setName("Jockccc");
        userDao.updateById(user2);            //version=6

        user.setName("Jocddd");
        userDao.updateById(user);             //version=5的条件不成立

结果:

 

 控制台:

 

posted @ 2023-02-18 22:01  佛系粥米  阅读(16)  评论(0)    收藏  举报