zoukankan      html  css  js  c++  java
  • mybatis-plus 乐观锁

    作用:保护数据安全,多线程下加锁

    过程:

    1、先查询,获取当前的版本号

    2、若版本号,不对则更新失败

    使用

    1、在数据库中添加version 字段

    2、实现类

    package com.wt.pojo;
    
    import com.baomidou.mybatisplus.annotation.*;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private String email;
        @Version
        private Integer version;
        @TableField(fill = FieldFill.INSERT)
        private Date createTime;
        @TableField(fill = FieldFill.INSERT_UPDATE)
        private Date updateTime;
    }

    3、新建配置类

    package com.wt.config;
    
    import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    
    @MapperScan("com.wt.mapper")
    @EnableTransactionManagement //
    @Configuration // 配置类
    public class MyBatisPlusConfig {
       @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); } }

    4、测试

    @Test
    // 乐观锁,模拟多线程, user1 更新失败, user2 更新成功
    public void testVersionLock(){
        // 1. 查询用户信息
        User user1 = userMapper.selectById(1);
        // 2.修改用户信息
        user1.setId(1L);
        user1.setName("ajax1");
    
        User user2 = userMapper.selectById(1);
        user2.setId(1L);
        user2.setName("ajax22");
    
        userMapper.updateById(user2);
        userMapper.updateById(user1);
    }
  • 相关阅读:
    这是一个关于Latex的测试
    在Mac下配置php开发环境:Apache+php+MySql
    CSS 颜色代码大全
    APP中关于Android和IOS与网页交互
    linux crontab
    dedecms中的内容页中的变量
    lamp中的Oracle数据库链接
    phpcms使用session的方法
    linux系统下nginx安装目录和nginx.conf配置文件目录
    window7+wamp环境配置Oracle数据库连接
  • 原文地址:https://www.cnblogs.com/wt7018/p/13354509.html
Copyright © 2011-2022 走看看