Springboot2整合Mybatisplus实现乐观锁

1.添加pom文件

  <!--  <version>2.1.5.RELEASE</version>Springboot版本 -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- mybatisPlus 核心库 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- 引入阿里数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

2.配置文件application.properties

server.port=8088

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

3.编写Mybatis-puls配置类

@Configuration
public class MybatisPlusConfig {

    //乐观锁配置
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
  //下面随意配置
    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    

    @Bean
    public RestTemplate getRestTemplate(){
        return  new RestTemplate();
    }

    //逻辑删除
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
}

4.编写entity对象

@Data  //注意需要下载lombok插件,不行就写get和set方法
@TableName("bank")
public class Bank implements Serializable {
    private static final long serialVersionUID = 1L;

    @TableId(type = IdType.AUTO)
    private Integer id;

    private Integer amount;

    @Version   //需要版本注解
    private Integer version;

    private Integer userId;

}

5.编写Mapper

@Mapper
public  interface BankMapper extends BaseMapper<Bank> {
}

6.编写Service

public interface BankSerice extends IService<Bank> {
}

7.编写实现层,根据业务场景去写,这里不详细说明了

@Service
public class BankSeviceImpl extends ServiceImpl<BankMapper,Bank> implements BankSerice {
    
}

8.编写控制层

@RestController
public class BankController {

    @Autowired
    BankSerice bankService;

    @RequestMapping("/bank/{userId}/{money}")
    public String access(@PathVariable("userId") String userId, @PathVariable("money") Integer money) throws InterruptedException {
        QueryWrapper<Bank> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Bank bank = bankService.getOne(queryWrapper);
        Integer amount = bank.getAmount();
        bank.setAmount(amount + money);
        Thread.sleep(5000);
        boolean b = bankService.updateById(bank);
        if (b) {
            return "更新成功";
        }
        return "更新失败,余额已被其他操作人员修改,请重试";
    }
}

9.数据库执行SQL

CREATE TABLE `bank` (
  `id` INT(11) NOT NULL,
  `amount` INT(10) DEFAULT NULL COMMENT '余额',
  `version` INT(5) DEFAULT NULL COMMENT '版本号',
  `user_id` INT(11) DEFAULT NULL COMMENT '用户id',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=INNODB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC



INSERT INTO bank (id,amount,VERSION,user_id) VALUES (1,100,0,2)

10.启动Springboot访问http://localhost:8088/bank/2/100

点击2次同时访问

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值