mybatis-plus高级(插件机制,通用service)三

7. 高级(插件机制)

7.1 自动填充

项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。

我们可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作:

7.1.1 原理

  • 实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler,确定填充具体操作
  • 注解填充字段:@TableField(fill = ...) 确定字段填充的时机
    • FieldFill.INSERT:插入填充字段
    • FieldFill.UPDATE:更新填充字段
    • FieldFill.INSERT_UPDATE:插入和更新填充字段

7.1.2 基本操作

  • 步骤一:修改表添加字段

    alter table tmp_customer add column create_time date;
    alter table tmp_customer add column update_time date;
    
  • 步骤二:修改JavaBean

    package com.czxy.mp.domain;
    
    import com.baomidou.mybatisplus.annotation.*;
    import lombok.Data;
    
    import java.util.Date;
    
    
    @Data
    @TableName("tmp_customer")
    public class Customer {
        @TableId(type = IdType.AUTO)
        private Integer cid;
        private String cname;
        private String password;
        private String telephone;
        private String money;
    
    @TableField(value="create_time",fill = FieldFill.INSERT)
    private Date createTime;
    
    @TableField(value="update_time",fill = FieldFill.UPDATE)
    private Date updateTime;
    
    }
    
  • 步骤三:编写处理类
    在这里插入图片描述

    package com.czxy.mp.handler;
    
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
    	/**
         * 插入填充
         * @param metaObject
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", new Date(), metaObject);
        }
    
        /**
         * 更新填充
         * @param metaObject
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
    
  • 步骤四:测试

      @Test
        public void testInsert() {
            Customer customer = new Customer();
            customer.setCname("测试888");
    
            customerMapper.insert(customer);
        }
    
        @Test
        public void testUpdate() {
            Customer customer = new Customer();
            customer.setCid(11);
            customer.setTelephone("999");
    
            customerMapper.updateById(customer);
        }
    

7.2 乐观锁

7.2.1 什么是乐观锁

  • 当要更新一条记录的时候,希望这条记录没有被别人更新

  • 乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

7.2.2. 实现

  • 步骤一:修改表结构,添加version字段
    在这里插入图片描述

  • 步骤二:修改JavaBean,添加version属性
    在这里插入图片描述

      package com.czxy.mp.domain;
      
      import com.baomidou.mybatisplus.annotation.*;
      import lombok.Data;
    
    
      @Data
      @TableName("tmp_customer")
      public class Customer {
          @TableId(type = IdType.AUTO)
          private Integer cid;
          private String cname;
          private String password;
          private String telephone;
          private String money;
          @Version
          @TableField(fill = FieldFill.INSERT)
          private Integer version;
      }
    
    
  • 步骤三:元对象处理器接口添加version的insert默认值 (保证version有数据)
    在这里插入图片描述

    package com.czxy.mp.config;
    
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        /**
         * 插入填充
         * @param metaObject
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("version", 1, metaObject);
        }
    
        /**
         * 更新填充
         * @param metaObject
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
    
  • 步骤四:修改 MybatisPlusConfig 开启乐观锁

    package com.czxy.mp.config;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
    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 MybatisPlusConfig {
        /**
         * 配置插件
         * @return
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
    
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            // 分页插件
            mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            // 乐观锁
            mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    
            return mybatisPlusInterceptor;
        }
    }
    
  • 步骤五:测试

    • 先添加一条,保证version有数据
    • 在更新该条
          @Test
          public void testUpdate() {
              Customer customer = new Customer();
              customer.setCid(14);
              customer.setCname("测试999");
              // 与数据库中数据一致,将更新成功,否则返回失败。
              customer.setVersion(1);
      
              int i = customerMapper.updateById(customer);
              System.out.println(i);
          }
      

7.2.3 注意事项

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • update(entity, wrapper) 方法下, wrapper 不能复用!!!

7.3 逻辑删除

7.3.1 什么是逻辑删除

  • 逻辑删除,也称为删除。就是在表中提供一个字段用于记录是否删除,实际该数据没有被删除。

7.3.2 实现

  • 步骤一:修改表结构添加deleted字段
    在这里插入图片描述

  • 步骤二:修改JavaBean,给deleted字段添加@TableLogic
    在这里插入图片描述

      package com.czxy.mp.domain;
      
      import com.baomidou.mybatisplus.annotation.*;
      import lombok.Data;
    
      @Data
      @TableName("tmp_customer")
      public class Customer {
          @TableId(type = IdType.AUTO)
          private Integer cid;
          private String cname;
          private String password;
          private String telephone;
          private String money;
          @Version
          @TableField(fill = FieldFill.INSERT)
          private Integer version;
    
          @TableLogic
          @TableField(fill = FieldFill.INSERT)
          private Integer deleted;
      }
    
  • 步骤三:添加数据时,设置默认“逻辑未删除值”
    在这里插入图片描述

    package com.czxy.mp.config;
    
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        /**
         * 插入填充
         * @param metaObject
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("version", 1, metaObject);
            this.setFieldValByName("deleted", 0, metaObject);
        }
    
        /**
         * 更新填充
         * @param metaObject
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
    
    
  • 步骤四:测试

        @Test
        public void testDelete() {
            // 删除时,必须保证deleted数据为“逻辑未删除值”
            int i = customerMapper.deleteById(12);
            System.out.println(i);
        }
    

7.3.3 全局配置

  • 如果使用了全局配置,可以不使用注解@TableLogic

    mybatis-plus:
      global-config:
        db-config:
          logic-delete-field: deleted  # 局逻辑删除的实体字段名
          logic-delete-value: 1  # 逻辑已删除值(默认为 1)
          logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    

8. 通用Service

  • 标准service:接口 + 实现
    在这里插入图片描述
    • service接口

        package com.czxy.service;
      
        import com.baomidou.mybatisplus.extension.service.IService;
        import com.czxy.domain.Customer;
      
        public interface CustomerService extends IService<Customer> {
        }
      
    • service实现类

      package com.czxy.service.impl;
      
      import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
      import com.czxy.domain.Customer;
      import com.czxy.mapper.CustomerMapper;
      import com.czxy.service.CustomerService;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;
      
      @Service
      @Transactional
      public class CustomerServiceImpl extends ServiceImpl<CustomerMapper,Customer> implements CustomerService {
      
      }
      
      
      • 具体方法
      import com.czxy.MybatisPlusApplication;
      import com.czxy.domain.Customer;
      import com.czxy.service.CustomerService;
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.springframework.boot.test.context.SpringBootTest;
      import org.springframework.test.context.junit4.SpringRunner;
      
      import javax.annotation.Resource;
      import java.util.List;
      
      /**
       * @ClassName TestDemo
       * @Description TODO
       * @Author Administrator
       * @Date 2021-12-21 10:50
       */
      @RunWith(SpringRunner.class)
      @SpringBootTest(classes = MybatisPlusApplication.class)
      public class TestDemo {
          @Resource
          CustomerService customerService;
      
          /**
           * 查询所有
           */
          @Test
          public void testList(){
              List<Customer> list = customerService.list();
              list.forEach(System.out::println);
          }
      
          /**
           * 添加
           */
          @Test
          public void testInsert(){
              Customer customer = new Customer();
              customer.setCname("888");
              customer.setPassword("888");
              customerService.save(customer);
          }
      
          /**
           * 更新
           */
          @Test
          public void testUpdate(){
              Customer customer = new Customer();
              customer.setCid(10);
              customer.setCname("999");
              customer.setPassword("999");
              customerService.updateById(customer);
          }
      
          /**
           * 删除
           */
          @Test
          public void testDelete(){
              customerService.removeById(10);
          }
      
          /**
           * 添加或更新
           */
          @Test
          public void testInsertOrUpdate(){
              Customer customer = new Customer();
              customer.setCid(10);
              customer.setCname("999");
              customer.setPassword("999");
              customerService.saveOrUpdate(customer);
          }
      }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值