• MyBatis-Plus


    1.入门案例

    1.建库&建表&添加数据

    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键id',
      `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
      `age` int(0) NULL DEFAULT NULL COMMENT '年龄',
      `email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES (1, '张三', 17, NULL);
    INSERT INTO `user` VALUES (2, '李四', 16, '123456@163.net');
    INSERT INTO `user` VALUES (3, '王五', 15, '352641@qq.com');
    INSERT INTO `user` VALUES (4, '赵六', 14, NULL);
    INSERT INTO `user` VALUES (5, '陈七', 13, '951463@263.net');
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2.新建springboot项目

    • 依赖

              
              <dependency>
                  <groupId>com.baomidougroupId>
                  <artifactId>mybatis-plus-boot-starterartifactId>
                  <version>3.4.1version>
              dependency>
              
              <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
                  <scope>runtimescope>
              dependency>
              
              <dependency>
                  <groupId>com.alibabagroupId>
                  <artifactId>druidartifactId>
                  <version>1.2.8version>
              dependency>
              
              <dependency>
                  <groupId>org.projectlombokgroupId>
                  <artifactId>lombokartifactId>
              dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
    • application.yml

      spring:
        # 配置数据源信息
        datasource:
          # 配置数据源类型
          type: com.alibaba.druid.pool.DruidDataSource
            # 配置连接数据库的信息
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT&characterEncoding=utf-8&useSSL=false
          username: root
          password: admin
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 注意:
        • spring boot 2.0(内置jdbc5驱动),spring boot 2.1及以上(内置jdbc8驱动)
          • jdbc5驱动:driver-class-name: com.mysql.jdbc.Driver
          • jdbc8驱动:driver-class-name: com.mysql.cj.jdbc.Driver
        • mysql连接地址url
          • mysql5.7:jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
          • mysql8.0:jdbc:mysql://localhost:3306/mybatis_plus? serverTimezone=UTC&characterEncoding=utf-8&useSSL=false

    3.新建实体类

    @Data
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    @Data lombok注解,内容如下:
    无参构造 + setter + getter + equals( hashCode ) + toString

    4.创建mapper接口并扫描

    UserMapper 接口:

    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3
    • UserMapper继承BaseMapper接口
    • @Repository
      将类或接口标识为持久层组件

    启动类扫描 UserMapper 接口:

    @SpringBootApplication
    @MapperScan("com.chenjy.mp_demo.mapper")
    public class MpDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MpDemoApplication.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • @MapperScan
      扫描mapper所在包或接口
    • 右键——copy path/xxx

    5.测试类测试

    @SpringBootTest
    class MpDemoApplicationTests {
        @Resource
        private UserMapper userMapper;
    
        /**
         * @Description 查询一个list集合,如果没有条件,就直接传参 null
        */
        @Test
        public void testGetAll() {
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    6.添加日志,显示查询语句

    配置文件:

      mybatis-plus:
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    • 1
    • 2
    • 3

    重新启动测试类,可以在控制台打印SQL语句:

    7.测试增删改查

    1.插入单条数据

        @Test
        public void testInsert() {
            User user = new User();
            user.setName("李华");
            System.out.println("flag: " + userMapper.insert(user));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意: mybatisplus默认使用雪花算法生成主键,如下图,这就是为啥要把id设为bigint类型并用Long接收。

    2.删除

    • deleteById

      @Test
      public void testDelete() {
          userMapper.deleteById(1569870313976463362L);
      }
      
      • 1
      • 2
      • 3
      • 4
    • deleteByMap

          @Test
          public void testDeleteByMap() {
              Map<String, Object> map = new HashMap<>();
              map.put("name", "张三");
              map.put("id", 1);
              userMapper.deleteByMap(map);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • testDeleteBatchIds

          @Test
          public void testDeleteBatchIds() {
              List<Long> list = Arrays.asList(2L, 3L);
              userMapper.deleteBatchIds(list);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    3.修改

    • updateById
          @Test
          public void testUpdate() {
              User user = new User();
              user.setId(4L);
              user.setName("小明");
              userMapper.updateById(user);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7

    4.查询

    • selectById

          @Test
          public void testSelect() {
              userMapper.selectById(4L);
          }
      
      • 1
      • 2
      • 3
      • 4
    • selectList

          @Test
          public void testSelectList() {
              userMapper.selectList(null);
          }
      
      • 1
      • 2
      • 3
      • 4
    • selectBatchIds

          @Test
          public void testSelectBatch() {
              List<Long> list = Arrays.asList(4L, 5L);
              userMapper.selectBatchIds(list);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • selectByMap

          @Test
          public void testSelectByMap() {
              Map<String, Object> map = new HashMap<>();
              map.put("id", 4);
              map.put("name", "小明");
              userMapper.selectByMap(map);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7

    8.测试自定义功能

    mybatis-plus.mapper-locations的默认路径是: classpath*:/mapper/**/*.xml,所以需要配置一下:

      mybatis-plus:
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        mapper-locations: classpath:/mapper/*.xml
    
    • 1
    • 2
    • 3
    • 4
    • resources.mapper 下创建一个映射文件 UserMapper

      
      DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
      <mapper namespace="com.chenjy.mp_demo.mapper.UserMapper">
      
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • UserMapper 接口中自定义方法

      Map<String, Object> selectMapById(Long id);
      
      • 1
    • UserMapper 中写SQL语句

          <select id="selectMapById" resultType="map">
              select
                     id,
                     name,
                     age,
                     email
              from
                   user
              where
                    id = #{id}
          select>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • 测试方法

          @Test
          public void testSelectMapById() {
              Map<String, Object> map = userMapper.selectMapById(4L);
              System.out.println(map);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    9.通用Service

    1.Service

    • 新建 UserService接口继承 IService 接口
      public interface UserService extends IService<User> {
      }
      
      • 1
      • 2
      • IService 接口:封装了常见的业务层逻辑,其实现类为 ServiceImpl
    • 新建 UserServiceImpl 实现 UserService接口
      @Service
      public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
      }
      
      • 1
      • 2
      • 3
      • 继承 ServiceImpl 是因为,UserService 继承了 IService 接口,如果不继承 ServiceImpl,则必须去实现 IService 接口的方法
      • 这时候, UserServiceImpl 既可以直接使用通用Service的功能,也能自定义新功能

    2.测试

    • count

      @SpringBootTest
      public class MPServiceTest {
      
          @Resource
          private UserService userService;
      
          @Test
          public void testGetCount() {
              userService.count();
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • saveBatch

          @Test
          public void testInsertBatch() {
              ArrayList<User> users = new ArrayList<>();
              for (int i = 0; i < 5; i++) {
                  User user = new User();
                  user.setName("张三" + i + "号");
                  user.setAge(13 + i);
                  users.add(user);
              }
              userService.saveBatch(users);
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

    2.Mybatis-plus常用注解

    1.@TableName

    @TableName 当数据库表名与实体类名不一致的时候使用

    • 场景演示,将数据库的表名更改为 mp_user,实体类名依然保持为 User,执行测试代码,报错如下:

    • 如何使用@TableName来解决上述报错:直接在实体类上添加 @TableName("mp_user")

      @Data
      @TableName("mp_user")
      public class User {
          private Long id;
          private String name;
          private Integer age;
          private String email;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8

    2.全局配置表名前缀

    当数据库所有的表的表名都有一个统一前缀的时候,如果使用@TableName就会显得繁琐,那么就需要用到 mybatis-plus全局配置 了。

    配置如下:

      mybatis-plus:
        # 设置mybatis-plus全局配置
        global-config:
          db-config:
          	# 设置表名统一前缀
            table-prefix: mp_
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.@TableId

    @TableId 将某个成员变量指定为数据表主键

    • 当实体类的主键字段名(id)与表中主键字段名(uid)不同时,使用
          @TableId("uid")
          private Long id;
      
      • 1
      • 2
    • value
      • 仅传入一个参数的时候的默认属性
      • 设置对应的数据库表的字段名
    • type
      • 设置id自增生成策略,默认使用雪花算法
        IdType type() default IdType.NONE;
        
        • 1
      • 如何设置为id自动递增算法?
        • 首先设置主键字段递增
        • type设置为递增策略
              @TableId(value = "uid", type = IdType.AUTO)
              private Long id;
          
          • 1
          • 2
      • 测试一下自动递增算法
        • 注意:先使用Navicat截断一下表(右键表名—截断表,即truncate 清除数据,保留结构,不写日志)

    注意: 当表中字段名为小驼峰写法时,mybatis-plus中会将其识别为_格式,如:userId(表名)→ user_id(mybatis-plus识别出来的名字)。

    4.全局配置主键生成策略

      mybatis-plus:
        global-config:
          db-config:
            # 配置主键生成策略
            id-type: auto
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.雪花算法概述

    雪花算法:

    • 概念:
      分布式环境下的一ID生成算法,能够保证不同表的主键的不重复性,以及相同表的主键的有序性
    • 应对场景:
      数据量和访问压力较大的场景
    • 核心思想
      • 长度共64bit(一个long型)
      • 首先是一个符号位,1bit标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0
      • 41bit时间截(毫秒级),存储的是时间截的差值(当前时间截 - 开始时间截),结果约等于69.73年
      • 10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID,可以部署在1024个节点)
      • 12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID)
    • 优点:整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高

    数据库的扩展方式

    • 业务分库
    • 主从复制
    • 数据库分表
      单表数据拆分有两种方式:垂直分表和水平分表
      • 垂直分表: 拆分 不常用且占了大量空间 的字段到其他表
      • 水平分表:表行数据量特别大 的进行分表存储数据
        • 主键自增: 以最常见的用户 ID 为例,可以按照 1000000 的范围大小进行分段,1 ~ 999999 放到表 1中,1000000 ~ 1999999 放到表2中,以此类推
          • 复杂点:分段大小的选取
          • 优点:可以随着数据的增加平滑地扩充新的表
          • 缺点:分布不均匀
        • 取模: 同样以用户 ID 为例,假如我们一开始就规划了 10 个数据库表,可以简单地用 user_id % 10 的值来表示数据所属的数据库表编号,ID 为 985 的用户放到编号为 5 的子表中,ID 为 10086 的用户放到编号为 6 的子表中
          • 复杂点:初始表数量的确定
          • 优点:表分布比较均匀
          • 缺点:扩充新的表很麻烦,所有数据都要重分布

    6.@TableFiled

    @TableFIled 解决实体类属性名与表的字段名不一致的问题。

    @Data
    public class User {
        @TableId(value = "uid")
        private Long id;
        @TableField("user_name")
        private String name;
        private Integer age;
        private String email;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    7.@TargetLogic

    逻辑删除:

    • 假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
    • 可以进行数据恢复

    代码演示:

    • 逻辑删除:

          @TableLogic(value = "1", delval = "0")
          private Integer status;
      
      • 1
      • 2
    • 测试代码:

          @Test
          public void testDelete() {
              userMapper.deleteById(1);
          }
      
      • 1
      • 2
      • 3
      • 4
          @Test
          public void testGetAll() {
              List<User> users = userMapper.selectList(null);
          }
      
      • 1
      • 2
      • 3
      • 4

    3.条件构造器和常用接口

    1.Wapper简介

    Wapper 条件构造抽象类,最顶端父类

    • AbstractWrapper: 用于查询条件封装,生成 sql 的 where 条件
      • QueryWrapper: 查询条件封装
      • UpdateWrapper:update条件封装
      • AbstractLambdaWrapper: 使用Lambda 语法
        • LambdaQueryWrapper: 用于Lambda语法使用的查询Wrapper
        • LambdaUpdateWrapper: Lambda 更新封装Wrapper

    2.QueryWrapper

    1.模糊查询

    @SpringBootTest
    public class MPMapperTest {
        @Resource
        private UserMapper userMapper;
    
        @Test
        public void test_01() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // user_name模糊查询,age在13到20之间,email不为空
            queryWrapper.like("user_name", "张")
                    .between("age", 13, 19)
                    .isNotNull("email");
            List<User> list = userMapper.selectList(queryWrapper);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.排序

        @Test
        public void test_02() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 查询用户信息,并按照年龄降序排序,若年龄相同,则按照id升序排序
            queryWrapper.orderByDesc("age")
                    .orderByAsc("uid");
            List<User> list = userMapper.selectList(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3.删除

        @Test
        public void test_03() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNull("email");
            userMapper.delete(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4.更新

        @Test
        public void test_04() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 将邮箱为空,且名字中有赵或周的用户的邮箱设置为testDemo04.net
            queryWrapper.isNull("email")
                    .like("user_name", "赵")
                    .or()
                    .like("user_name", "周");
            // 会将实体类中设置的字段作为修改后的值
            User user = new User();
            user.setEmail("testDemo04.net");
            userMapper.update(user, queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    注意: 不能添加逻辑删除标志位为判断条件!!!

    5.条件优先级

        @Test
        public void test_05() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 将用户名中包含张,且年龄大于15或email为空的用户的email设为testDemo05.net
            // lambda表达式中的条件会优先执行
            queryWrapper.like("user_name", "张")
                    .and(el -> el.gt("age", 15).or().isNull("email"));
            // 会将实体类中设置的字段作为修改后的值
            User user = new User();
            user.setEmail("testDemo05.net");
            userMapper.update(user, queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    6.组装select语句

        @Test
        public void test_06() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 查询用户名、年龄、邮箱
            queryWrapper.select("user_name", "age", "email");
            List<Map<String, Object>> map = userMapper.selectMaps(queryWrapper);
            map.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    7.组装子查询

        @Test
        public void test_07() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 查询id <= 5 的用户id
            queryWrapper.inSql("uid", "select uid from mp_user where uid < 5");
            List<User> list = userMapper.selectList(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.UpdateWrapper

    UpdateWrapper 不同于 QueryWrapperUpdateWrapper 不仅可以设置修改条件,还能设置修改字段,也就不用去实例化一个对象来存储修改后的数据。

    1.修改

        @Test
        public void test_08() {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            // 修改用户名中有张,并且年龄大于15,id小于6
            updateWrapper.like("user_name", "张")
                    .and(el -> el.gt("age", 15)
                            .or()
                            .lt("uid", 6));
            updateWrapper.set("user_name", "宋青书").set("email", "95682314@163.net");
            userMapper.update(null, updateWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.模拟按需组装条件

    开发中,常常需要根据用户的选择来组装SQL语句。

    1.写法1.0

        @Test
        public void test_09() {
            // 模拟从前台接收的数据
            String name = "";
            Integer ageBegin = 14;
            Integer ageEnd = 17;
    
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            /*
                判断如何组装条件
                    选择mybatis-plus的StringUtils
             */
            if (StringUtils.isNotBlank(name)) {
                queryWrapper.like("user_name", name);
            }
            if (ageBegin != null) {
                queryWrapper.gt("age", ageBegin);
            }
            if (ageEnd != null) {
                queryWrapper.lt("age", ageEnd);
            }
            List<User> list = userMapper.selectList(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2.写法2.0

    对写法1.0进行简化升级。

        @Test
        public void test_10() {
            // 模拟从前台接收的数据
            String name = "";
            Integer ageBegin = 14;
            Integer ageEnd = 17;
    
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            /*
                判断如何组装条件
                    选择mybatis-plus的StringUtils
             */
            queryWrapper.like(StringUtils.isNotBlank(name), "user_name", name)
                    .gt(ageBegin != null, "age", ageBegin)
                    .lt(ageEnd != null, "age", ageEnd);
            List<User> list = userMapper.selectList(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    5.LambdaQueryWrapper

    1.模拟按需组装条件

    使用Lambda表达式简化代码,可以避免写错表字段名:

        @Test
        public void test_11() {
            // 模拟从前台接收的数据
            String name = "";
            Integer ageBegin = 14;
            Integer ageEnd = 17;
    
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            /*
                判断如何组装条件
                    选择mybatis-plus的StringUtils
             */
            queryWrapper.like(StringUtils.isNotBlank(name), User::getName, name)
                    .gt(ageBegin != null, User::getAge, ageBegin)
                    .lt(ageEnd != null, User::getAge, ageEnd);
            List<User> list = userMapper.selectList(queryWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    6.LambdaUpdateWrapper

    1.修改

        @Test
        public void test_12() {
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            // 修改用户名中有张,并且年龄大于15,id小于6
            updateWrapper.like(User::getName, "张")
                    .and(el -> el.gt(User::getAge, 15)
                            .or()
                            .lt(User::getId, 6));
            updateWrapper.set(User::getName, "宋青书").set(User::getEmail, "95682314@163.net");
            userMapper.update(null, updateWrapper);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.插件

    1.分页插件

    MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能

    1.添加配置类

    @Configuration
    @MapperScan("com.chenjy.mp_demo.mapper")
    public class MPConfig {
        @Bean
        public MybatisPlusInterceptor plusInterceptor() {
            // 使用插件需要使用到的类
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 添加分页插件(PaginationInnerInterceptor)到interceptor实例中
            // DbType 指定数据库类型为 MySQL
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            // 返回实例
            return interceptor;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2.测试分页插件

    @SpringBootTest
    public class MPPluginsTest {
        @Resource
        private UserMapper userMapper;
    
        @Test
        public void testPage() {
            Page<User> page = new Page<>(1, 5);
            userMapper.selectPage(page, null);
            System.out.println(page);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.Page常用方法

    • getRecords 查询数据列表
    • getPages 查询当前分页总页数
    • getTotal 查询数据总数
    • hasNext 判断是否存在下一页
    • hasPrevious 是否存在上一页

    4.自定义分页功能

    1.自定义分页方法
    • UserMapper 中自定义方法:

          /**
           * @Description 通过年龄查询用户信息并返回
           * @param page mp提供的分页对象,必须是参数列表第一个参数
           * @param age 
           * @return Page
          */
          Page<User> selectPagePo(@Param("page") Page<User> page, @Param("age") Integer age);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • UserMapper.xml 中写SQL

          <select id="selectPagePo" resultType="com.chenjy.mp_demo.pojo.User">
              select 
                     uid, 
                     user_name, 
                     age, 
                     email 
              from 
                   mp_user 
              where 
                    age > #{age}
          select>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    2.测试类
        @Test
        public void testPagePo(){
            Page<User> page = new Page<>(1, 5);
            userMapper.selectPagePo(page, 15);
            System.out.println(page.getRecords());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    配置类型别名:

    • application.yml 中配置包的类型别名

        mybatis-plus:
          type-aliases-package: com.chenjy.mp_demo.pojo
      
      • 1
      • 2
    • 之后,包下的类就可以直接将类名作为别名传入 resultType

          <select id="selectPagePo" resultType="User">
              select 
                     uid, 
                     user_name, 
                     age, 
                     email 
              from 
                   mp_user 
              where 
                    age > #{age}
          select>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    3.注意事项
    • 自定义分页方法,其返回类型必须是Page
    • 自定义分页方法的参数列表第一个参数必须是Page page
    • @Param mybatis注解
      • 作用——给参数命名
        如:@Param("id") int uid,就是外部想要给 uid 赋值或取值,只需要取它的参数名 id 就可以了,然后在SQL语句中,通过 #{id} 进行取值给SQL的参数赋值
      • 注意:
        • 使用@Param,SQL语句取值可以使用#{}${}
        • 不使用@Param
          • SQL语句取值只能使用#{}
          • 参数只能有一个,并且是Javabean

    2.乐观锁插件

    1.乐观锁与悲观锁的概念

    乐观锁:

    • 在操作数据时非常乐观,认为别人不会同时修改数据
    • 操作数据时不会上锁,只是在执行更新的时候判断一下在此期间别人是否修改了数据:如果别人修改了数据则放弃操作,否则执行操作

    悲观锁:

    • 在操作数据时比较悲观,认为别人会同时修改数据
    • 操作数据时直接把数据锁住,直到操作完成后才会释放锁;上锁期间其他人不能修改数据

    两锁详解:https://zhuanlan.zhihu.com/p/95296289

    2.演示数据不一致

    • 数据库搭建:

      -- ----------------------------
      -- Table structure for mp_product
      -- ----------------------------
      DROP TABLE IF EXISTS `mp_product`;
      CREATE TABLE `mp_product`  (
        `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
        `NAME` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品名称',
        `price` int(0) NULL DEFAULT 0 COMMENT '价格',
        `VERSION` int(0) NULL DEFAULT 0 COMMENT '乐观锁版本号',
        PRIMARY KEY (`id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
      
      -- ----------------------------
      -- Records of mp_product
      -- ----------------------------
      INSERT INTO `mp_product` VALUES (1, '蓝牙耳机', 198, 0);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
    • 实体类:

      @Data
      public class Product {
          private Long id;
          private String name;
          private Integer price;
          private Integer version;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • ProductMapper 接口:

      @Repository
      public interface ProductMapper extends BaseMapper<Product> {
      }
      
      • 1
      • 2
      • 3
    • 测试类:

          @Test
          public void testProduct01(){
              //小李查询商品价格
              Product productLi = productMapper.selectById(1);
              System.out.println("小李查询的商品价格:"+productLi.getPrice());
              //小王查询商品价格
              Product productWang = productMapper.selectById(1);
              System.out.println("小王查询的商品价格:"+productWang.getPrice());
              //小李将商品价格+50
              productLi.setPrice(productLi.getPrice()+50);
              productMapper.updateById(productLi);
              //小王将商品价格-30
              productWang.setPrice(productWang.getPrice()-30);
              int result = productMapper.updateById(productWang);
              //老板查询商品价格
              Product productLaoban = productMapper.selectById(1);
              System.out.println("老板查询的商品价格:"+productLaoban.getPrice());
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18

    分析: 没有保证数据的一致性,发生了数据冲突

    • 理想情况:

    • 实际情况:

    3.乐观锁优化上述案例

    • 给实体类的 version 属性加上 @Version 标识乐观锁的版本号

      @Version //标识乐观锁版本号字段
      private Integer version;
      
      • 1
      • 2
    • 在配置类中添加上乐观锁插件

      @Configuration
      @MapperScan("com.chenjy.mp_demo.mapper")
      public class MPConfig {
          @Bean
          public MybatisPlusInterceptor plusInterceptor() {
              // 使用插件需要使用到的类
              MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
              // 添加分页插件(PaginationInnerInterceptor)到interceptor实例中
              // DbType 指定数据库类型为 MySQL
              interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
              // 添加乐观锁插件
              interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
              // 返回实例
              return interceptor;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
    • 优化测试方法,让小王第一次修改之后,能再次获取版本号,继续修改

          @Test
      public void testProduct_01() {
          //小李查询商品价格
          Product productLi = productMapper.selectById(1);
          System.out.println("小李查询的商品价格:"+productLi.getPrice());
          //小王查询商品价格
          Product productWang = productMapper.selectById(1);
          System.out.println("小王查询的商品价格:"+productWang.getPrice());
          //小李将商品价格+50
          productLi.setPrice(productLi.getPrice()+50);
          productMapper.updateById(productLi);
          //小王将商品价格-30
          productWang.setPrice(productWang.getPrice()-30);
          int result = productMapper.updateById(productWang);
          if(result == 0){
              /*
                  操作失败,重试
                      即之前版本号已被修改,现在重新获取一个版本号,再来修改
               */
              Product productNew = productMapper.selectById(1);
              productNew.setPrice(productNew.getPrice()-30);
              productMapper.updateById(productNew);
          }
          //老板查询商品价格
          Product productLaoban = productMapper.selectById(1);
          System.out.println("老板查询的商品价格:"+productLaoban.getPrice());
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
    • 恢复数据库数据为 198,重新启动测试方法

    注意:

    • 测试乐观锁插件的时候,一定要保证数据库中的version字段有值(不能为null),否则插件无法生效
    • 不使用乐观锁的更新语句:
    • 使用乐观锁之后的更新语句

    5.通用枚举

    表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举来实现

    1.mp_user表新添sex字段

    • 表:

    • 实体类:

      @Data
      // @TableName("mp_user")
      public class User {
          @TableId(value = "uid")
          private Long id;
          @TableField("user_name")
          private String name;
          private Integer age;
          private String email;
          @TableLogic(value = "1", delval = "0")
          private Integer status;
          private SexEnum sex;// 枚举sex字段
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

    2.新建枚举类

    @Getter
    public enum SexEnum {
        MALE(1, "男"),
        FEMALE(0, "女");
    
        @EnumValue // 将注解所标识的值存储到数据库中
        private Integer sex;
        private String sexName;
    
        SexEnum(Integer sex, String sexName) {
            this.sex = sex;
            this.sexName = sexName;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3.配置文件配置扫描枚举

    • application.yml 配置扫描通用枚举的包

        mybatis-plus:
          # 扫描通用枚举的包
          type-enums-package: com.chenjy.mp_demo.enums
      
      • 1
      • 2
      • 3

    4.测试类

    @SpringBootTest
    public class MPEnumTest {
        @Resource
        private UserMapper userMapper;
    
        @Test
        public void testEnum() {
            User user = new User();
            user.setSex(SexEnum.MALE);
            user.setName("王重阳");
            user.setAge(39);
            userMapper.insert(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    6.代码生成器

    1.引入依赖

            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-generatorartifactId>
                <version>3.5.1version>
            dependency>
            <dependency>
                <groupId>org.freemarkergroupId>
                <artifactId>freemarkerartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.测试类

    @SpringBootTest
    public class MPAutoGeneratorTest {
    
        public static void main(String[] args) {
            FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&userSSL=false", "root", "admin")
                    .globalConfig(builder -> {
                        builder.author("chenjy") // 设置作者
                                //.enableSwagger() // 开启 swagger 模式
                                .fileOverride() // 覆盖已生成文件
                                .outputDir("D:\\mybatisplus\\demo1"); // 指定输出目录
                    })
                    // 最终生成的代码会存在com.chenjy.mybatisplus之下
                    .packageConfig(builder -> {
                        builder.parent("com.chenjy") // 设置父包名
                                .moduleName("mybatisplus") // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\Study\\projects\\se\\mp_demp")); // 设置mapperXml生成路径
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude("mp_user", "mp_product") // 设置需要生成的表名
                                .addTablePrefix("mp_", "t_"); // 设置过滤表前缀(可以设置多个前缀)
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                    .execute();// 执行
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    7.多数据源

    1.搭建两个数据库

    USE mp_demo1;
    
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键id',
      `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
      `age` int(0) NULL DEFAULT NULL COMMENT '年龄',
      `email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES (1, '张三', 17, NULL);
    INSERT INTO `user` VALUES (2, '李四', 16, '123456@163.net');
    INSERT INTO `user` VALUES (3, '王五', 15, '352641@qq.com');
    INSERT INTO `user` VALUES (4, '赵六', 14, NULL);
    INSERT INTO `user` VALUES (5, '陈七', 13, '951463@263.net');
    
    USE mp_demo2;
    
    -- ----------------------------
    -- Table structure for mp_product
    -- ----------------------------
    DROP TABLE IF EXISTS `mp_product`;
    CREATE TABLE `mp_product`  (
      `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `NAME` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品名称',
      `price` int(0) NULL DEFAULT 0 COMMENT '价格',
      `VERSION` int(0) NULL DEFAULT 0 COMMENT '乐观锁版本号'
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of mp_product
    -- ----------------------------
    INSERT INTO `mp_product` VALUES (1, '蓝牙耳机', 188, 0);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    2.新建springboot项目

    1.依赖

            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.4.1version>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.2.8version>
            dependency>
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
    
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>dynamic-datasource-spring-boot-starterartifactId>
                <version>3.1.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    2.配置文件

    spring:
      # 配置数据源信息
      datasource:
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        dynamic:
          # 设置默认的数据源或者数据源组,默认值即为master
          primary: master
          # 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
          strict: true
          datasource:
            master: # 可随意取名
              url: jdbc:mysql://localhost:3306/mp_demo1?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: admin
            slave_1: # 可随意取名
              url: jdbc:mysql://localhost:3306/mp_demo2?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: admin
            # druid配置,可直接使用默认值
            druid:
              #初始化时建立物理连接的个数
              initialSize: 1
              #池中最大连接数
              maxActive: 20
              #最小空闲连接
              minIdle: 1
              #获取连接时最大等待时间,单位毫秒
              maxWait: 60000
    
    server:
      port: 8089
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    3.实体类

    @Data
    @TableName("mp_product")
    public class Product {
        private Integer id;
        private String name;
        private Integer price;
        private Integer version;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    @Data
    public class User {
        private Integer id;
        private String name;
        private Integer age;
        private String email;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4.mapper接口

    @Repository
    public interface ProductMapper extends BaseMapper<Product> {
    }
    
    • 1
    • 2
    • 3
    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3

    4.service

    1.接口

    public interface ProductService extends IService<Product> {
    }
    
    • 1
    • 2
    public interface UserService extends IService<User> {
    }
    
    • 1
    • 2

    2.实现类

    @Service
    @DS("slave_1")// 设置要操作的数据源
    public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    }
    
    • 1
    • 2
    • 3
    • 4
    @Service
    @DS("master") // 设置要操作的数据源 
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    }
    
    • 1
    • 2
    • 3
    • 4

    @DS

    • 切换数据源
    • 可以写在方法上或类上
      @Target({ElementType.TYPE, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      public @interface DS {
          String value();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6

    5.测试类

    @SpringBootTest
    class MpDemo1ApplicationTests {
        @Resource
        private UserService userService;
        @Resource
        private ProductService productService;
    
        @Test
        public void testSelect() {
            System.out.println(userService.getById(1));
            System.out.println(productService.getById(1));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    注意: 别忘了在启动类上添加 @MapperScan 注解扫描mapper包。

    8.MyBatisX插件

    MyBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率。

    但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可以使用MyBatisX插件。

    最简单且实用功能:

    • 快速定位 mapper接口 及其 mapper.xml映射文件
      点击小鸟,可以飞来飞去

    1.代码快速生成

    1.案例

    1.新建springboot项目导入依赖
    • 依赖

              <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
              dependency>
              <dependency>
                  <groupId>com.baomidougroupId>
                  <artifactId>mybatis-plus-boot-starterartifactId>
                  <version>3.4.1version>
              dependency>
              <dependency>
                  <groupId>com.alibabagroupId>
                  <artifactId>druidartifactId>
                  <version>1.2.8version>
              dependency>
              <dependency>
                  <groupId>org.projectlombokgroupId>
                  <artifactId>lombokartifactId>
              dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
    2.连接database,快速生成代码
    • 快速生成流程





    • 配置:

      spring:
        datasource:
          # 配置数据源类型
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT&characterEncoding=utf-8&useSSL=false
          username: root
          password: admin
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8

    2.快速生成CRUD

    • 插入:



    • 删除:




    • 修改

    • 查询

    9.代码下载地址

    https://github.com/Crashinging/mybatis-plus

    git@github.com:Crashinging/mybatis-plus.git
    
    • 1
  • 相关阅读:
    C. Random Events(思维+概率)
    原码,反码,补码 以及 位运算
    SpringMVC学习笔记
    树的存储结构以及树,二叉树,森林之间的转换
    设计模式之原型模式
    五个人的五个成绩
    2022年鲜为人知的CSS 特性了解起来~
    【FPGA教程案例33】通信案例3——基于FPGA的BPSK调制信号产生,通过matlab测试其星座图
    go 服务接入短信验证码功能(对接阿里云平台)
    英语词汇篇 - 词性的转化
  • 原文地址:https://blog.csdn.net/m0_54355172/article/details/126345996