MyBatisPlus 使用指南 自动更新 软删除 乐观锁

MyBatisPlus 使用指南 自动更新 软删除 乐观锁 关联查询

快速入门

步骤java

  1. 建立数据库,数据表

  1. 使用SpringBoot导入maven依赖mysql

    <!-- 数据库驱动 -->
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
    
            <!-- lombok -->
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
            <!-- mybatis-plus -->
            <!-- mybatis-plus 是本身开发,并不是官方的! -->
            <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.2</version>
            </dependency>
  2. 使用了mybatis-plus 以后(区别于mybatis传统方式entity-dao(链接mybatis,配置mapper.xml文件)-service-controller)sql

    • 实体类:数据库

      @Data
      public class User  {
      
          /**
           * 主键ID
           */
          @TableId(value = "id", type = IdType.AUTO)
          private Long id;
      
          /**
           * 姓名
           */
          private String name;
      
          /**
           * 年龄
           */
          private Integer age;
      
          /**
           * 邮箱
           */
          private String email;
      
      }
    • mapper接口mybatis

      //对应的的Mapper上面继承基本的类 BaseMapper
      @Repository
      public interface UserMapper extends BaseMapper<User> {
      	//通用CRUD操做父类已经写好
      }
    • 注意点,咱们须要在主启动类上去扫描咱们的mapper包下的全部接口app

      @MapperScan("com.mybatis.mybatis_plus.mapper")maven

    • 测试类中能够测试:ide

      @Autowired
          private UserMapper userMapper;
          @Test
          void contextLoads() {
      
              List<User> userList = userMapper.selectList(null);
              userList.forEach(System.out::println);
      
          }

自动更新

全部的数据库表:gmt_create、gmt_modified几乎全部的表都要配置上!并且需 要自动化!测试

一、在表中新增字段 gmt_create、gmt_modified,类型datetimethis

二、把实体类同步,实体类字段属性上须要增长注解

@TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

三、编写handler来处理这个注解!

@Slf4j
@Component // 注意加到ioc容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
        // 插入时的填充策略
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("gmtCreate",new Date(),metaObject);
            this.setFieldValByName("gmtModified",new Date(),metaObject);
        }
        // 更新时的填充策略
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("gmtModified",new Date(),metaObject);
        }
}

四、测试插入、测试更新、观察时间便可。

软删除(逻辑删除)

物理删除 :从数据库中直接移除

逻辑删除 :再数据库中没有被移除,而是经过一个变量来让他失效! deleted = 0 => deleted = 1

一、在数据表中增长一个 deleted 字段

二、实体类中增长属性

/**
     * 是否删除,1已删除,0未删除
     */
    @TableLogic
    private Boolean deleted;

三、配置!

# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

新版本Mybatislus无需一下配置了

@Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }

四、测试一下删除! 记录依旧在数据库,可是值确已经变化了,查询也不会显示被删除的数据!

int i = userMapper.deleteById(2L);
System.out.println(i);
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);

乐观锁

乐观锁 : 故名思意十分乐观,它老是认为不会出现问题,不管干什么不去上锁!若是出现了问题, 再次更新值测试

悲观锁:故名思意十分悲观,它老是认为老是出现问题,不管干什么都会上锁!再去操做!

咱们这里主要讲解 乐观锁机制!

乐观锁实现方式:

  • 取出记录时,获取当前 version

  • 更新时,带上这个version

  • 执行更新时, set version = newVersion where version = oldVersion

  • 若是version不对,就更新失败

    乐观锁:一、先查询,得到版本号 version = 1
    -- A
    update user set name = "tom", version = version + 1
    where id = 2 and version = 1
    -- B 线程抢先完成,这个时候 version = 2,会致使 A 修改失败!
    update user set name = "jack", version = version + 1
    where id = 2 and version = 1

在MyBatisPlus里面使用乐观锁插件

一、给数据添加version字段,整型默认值为1。

二、实体类添加对应字段

@Version //乐观锁Version注解
    private Integer version;

三、注册组件

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

四、测试

// 测试乐观锁成功!
@Test
public void testOptimisticLocker(){
    // 一、查询用户信息
    User user = userMapper.selectById(1L);
    // 二、修改用户信息
    user.setName("Simon");
    // 三、执行更新操做
    userMapper.updateById(user);
}

能够看到更新执行的sql

相关文章
相关标签/搜索