对Mybatis-Plus的爱不释手

MyBatis-Plus

1. 简介

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

2. 能干什么

2.1 特性

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2.2 常用注解

2.2.1 @TableName

描述:表名注解

属性类型必须指定默认值描述
valueString“”表名
schemaString“”schema
keepGlobalPrefixbooleanfalse是否保持使用全局的 tablePrefix 的值(如果设置了全局 tablePrefix 且自行设置了 value 的值)
resultMapString“”xml 中 resultMap 的 id
autoResultMapbooleanfalse是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入)
2.2.2 @TableId

描述:主键注解

属性类型必须指定默认值描述
valueString“”主键字段名
typeEnumIdType.NONE主键类型

IdType

描述
AUTO数据库ID自增
NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUTinsert前自行set主键值
ASSIGN_ID分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)
2.2.3 @TableField

描述:字段注解(非主键)

属性类型必须指定默认值描述
valueString“”数据库字段名
elString“”映射为原生 #{ ... } 逻辑,相当于写在 xml 里的 #{ ... } 部分
existbooleantrue是否为数据库表字段
fillEnumFieldFill.DEFAULT字段自动填充策略

FieldFill

描述
DEFAULT默认不处理
INSERT插入时填充字段
UPDATE更新时填充字段
INSERT_UPDATE插入和更新时填充字段
2.2.4 @Version

描述:乐观锁注解、标记 @Verison 在字段上

2.2.5 @TableLogic

描述:表字段逻辑处理注解(逻辑删除)

属性类型必须指定默认值描述
valueString“”逻辑未删除值
delvalString“”逻辑删除值

3. 怎么玩

项目环境在spring boot 工程的基础上搭建!!!

  1. 引入依赖

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.2</version>
    </dependency>
    
  2. 添加配置

    server:
      port: 8001
    spring:
      application:
        name: mp
      datasource:
        url: jdbc:mysql://localhost:3306/hotel?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
        username: root
        password: xxxxxx
    mybatis-plus:
      global-config:
        db-config:
          logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
          logic-delete-value: 1 # 逻辑已删除值(默认为 1)
          logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    
  3. Java Bean

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @TableName(value = "user")
    public class User {
        @TableId(type = IdType.ASSIGN_ID)
        private Long id;
        private String name;
        private String password;
        @TableField(fill = FieldFill.INSERT)
        private Date createTime;
        @TableField(fill = FieldFill.INSERT_UPDATE)
        private Date updateTime;
        @TableLogic
        private Integer flag;
        @Version
        private Integer version;
    }
    
  4. 配置类

    @EnableTransactionManagement  // 乐观锁,开启事务
    @Configuration
    @MapperScan(value = "com.codelnn.springboot.mapper")
    public class MyBatisPlusConfig {
        /**
         * id生成器
         *
         * new DefaultIdentifierGenerator()  雪花算法
         *  new CustomIdGenerator(); 自定义id实现
         */
        @Bean
        public IdentifierGenerator idGenerator() {
            return new DefaultIdentifierGenerator();
    
        }
        /**
         * 乐观锁
         * 取出记录时,获取当前version
         * 更新时,带上这个version
         * 执行更新时, set version = newVersion where version = oldVersion
         * 如果version不对,就更新失败
         * 说明:
         *
         * 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
         * 整数类型下 newVersion = oldVersion + 1
         * newVersion 会回写到 entity 中
         * 仅支持 updateById(id) 与 update(entity, wrapper) 方法
         * 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
         */
        @Bean
        public OptimisticLockerInterceptor optimisticLockerInterceptor() {
            return new OptimisticLockerInterceptor();
        }
        /**
         * 分页插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
            // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
            // paginationInterceptor.setOverflow(false);
            // 设置最大单页限制数量,默认 500 条,-1 不受限制
            // paginationInterceptor.setLimit(500);
            // 开启 count 的 join 优化,只针对部分 left join
            paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
            return paginationInterceptor;
        }
    
    }
    
    
  5. 自动填充时间

    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime",new Date(),metaObject);
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    }
    
    
  6. 自定义ID生成器

    public class CustomIdGenerator implements IdentifierGenerator {
        private final AtomicLong al = new AtomicLong(1);
        @Override
        public Number nextId(Object entity) {
            final long id = al.getAndAdd(1);
            return id;
        }
    }
    
  7. Service服务层

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public User selectByNameAndPassword(String name, String password) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name",name).eq("password",password);
            return userMapper.selectOne(queryWrapper);
        }
    
        @Override
        public Boolean deleteById(Long id) {
            int i = userMapper.deleteById(id);
            return i > 0;
        }
    
        @Override
        public void insertUser(User user) {
            user.setFlag(0);
            userMapper.insert(user);
        }
    
        @Override
        public void updateUser(User user) {
            User user1 = userMapper.selectById(user.getId());
            user1.setPassword(user.getPassword());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
             int re = userMapper.updateById(user1);
             if (re > 0){
                 System.out.println("更新成功");
             }else {
                 System.out.println("更新失败!!");
             }
        }
    
        @Override
        public User selectById(Long id) {
            return userMapper.selectById(id);
        }
    }
    
  8. 条件构造

    1. QueryWrapper 查询条件构造器
    2. UpdateWrapper 更新条件构造器

    参照官网 https://baomidou.com/guide/wrapper.html#abstractwrapper

4. 小总结

在开发中使用mybatis-plus,省去了写简单CRUD的步骤,让开发变得迅速,高效起来。

个人在开发中经常用到的点如下

  1. 逻辑删除 (在业务开发中,数据库数据一般都是逻辑删除)
  2. 自动填充功能 (自动填充时间字段)
  3. 分页功能 (一般页面展示会进行分页处理)
  4. 主键ID (默认雪花算法)
  5. 乐观锁的使用

本篇文章 查阅官方文档所写

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值