• MyBatis-Plus 笔记(二)


    6、条件构造器

    Wrapper介绍

    Untitled

    • Wrapper : 条件构造抽象类,最顶端父类
      • AbstractWrapper: 用于查询条件封装,生成 sql 的 where 条件
        • QueryWrapper: 查询条件封装
        • UpdateWrapper: Update 条件封装
        • AbstractLambdaWrapper: 使用Lambda 语法
          • LambdaQueryWrapper:用于Lambda语法使用的查询Wrapper
          • LambdaUpdateWrapper: Lambda 更新封装Wrapper

    QueryWrapper

    • 组装查询条件

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)

    		/**
         * 查询用户名包含a,年龄在20到30之间,邮箱信息不为null的用户信息
         */
        @Test
        public void test01() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_name", "a").between("age", 20, 30).isNotNull("email");
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 组装排序条件

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,uid ASC

    		/**
         * 查询用户信息,按照年龄的降序排序,若年龄相同,则按照id升序排序
         */
        @Test
        public void test02() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("age").orderByAsc("uid");
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 组装删除条件

    执行 SQL:UPDATE t_user SET is_deleted=1 WHERE is_deleted=0 AND (email IS NULL)

    		/**
         * 删除邮箱地址为null的用户信息
         */
        @Test
        public void test03() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNull("email");
            int result = userMapper.delete(queryWrapper);
            System.out.println(result > 0 ? "删除成功!" : "删除失败!");
            System.out.println("受影响的行数为:" + result);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 条件的优先级

    执行SQL:UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (age > ? AND user_name LIKE ? OR email IS NULL)

    		/**
         * 将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
         */
        @Test
        public void test04() {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            // 大于用gt
            updateWrapper.gt("age", 20).like("user_name", "a").or().isNull("email");
            User user = new User();
            user.setName("小明");
            user.setEmail("test@qq.com");
            int result = userMapper.update(user, updateWrapper);
            System.out.println(result > 0 ? "修改成功!" : "修改失败!");
            System.out.println("受影响的行数为:" + result);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    执行 SQL:UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))

    /**
         * 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
         */
        @Test
        public void test05() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // lambda表达式中的条件优先执行,gt表示大于
            queryWrapper.like("user_name", "a").and(i -> i.gt("age", 20).or().isNull("email"));
            User user = new User();
            user.setName("小红");
            user.setEmail("test@qq.com");
            int result = userMapper.update(user, queryWrapper);
            System.out.println(result > 0 ? "修改成功!" : "修改失败!");
            System.out.println("受影响的行数为:" + result);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 组装select子句

    执行 SQL:SELECT user_name,age,email FROM t_user WHERE is_deleted=0

    		/**
         * 查询用户的用户名、年龄、邮箱信息
         */
        @Test
        public void test06() {
            //SELECT user_name,age,email FROM t_user WHERE is_deleted=0
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("user_name", "age", "email");
            List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
            maps.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 实现子查询

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (uid IN (select uid from t_user where uid <= 100))

    		/**
         * 查询id小于等于100的用户信息(要求用子查询)
         */
        @Test
        public void test07() {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.inSql("uid", "select uid from t_user where uid <= 100");
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    UpdateWrapper

    UpdateWrapper不仅拥有QueryWrapper的组装条件功能,还提供了set方法修改对应条件的数据库信息

    执行 SQL:UPDATE t_user SET user_name=?,email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))

    		/**
         * 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
         */
        @Test
        public void test08() {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.like("user_name", "a").and(i -> i.gt("age", 20).or().isNull("email"));
            updateWrapper.set("user_name", "小黑").set("email", "abc@atguigu.com");
            int result = userMapper.update(null, updateWrapper);
            System.out.println("受影响的行数为:" + result);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    condition

    在真正开发的过程中,组装条件是常见的功能,而这些条件数据来源于用户输入,是可选的。因此我们在组装这些条件时,必须先判断用户是否选择了这些条件,若选择则需要组装该条件,若没有选择则一定不能组装,以免影响SQL执行的结果

    思路一:

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age <= ?)

    import com.baomidou.mybatisplus.core.toolkit.StringUtils;		
    
    		@Test
        public void test09() {
            String username = "a";
            Integer ageBegin = null;
            Integer ageEnd = 30;
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(username)) {
                //isNotBlank:判断某个字符串是否不为空字符串、不为null、不为空白符
                queryWrapper.like("user_name", username);
            }
            if (ageBegin != null) {
                // ge表示大于等于
                queryWrapper.ge("age", ageBegin);
            }
            if (ageEnd != null) {
                // le表示小于等于
                queryWrapper.le("age", ageEnd);
            }
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    思路二:

    上面的实现方案没有问题,但是代码比较复杂,我们可以使用带condition参数的重载方法构建查询条件,简化代码的编写

    import com.baomidou.mybatisplus.core.toolkit.StringUtils;		
    	
    		@Test
        public void test10() {
            String username = "a";
            Integer ageBegin = null;
            Integer ageEnd = 30;
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // ge表示大于等于,le表示小于等于
            queryWrapper.like(StringUtils.isNotBlank(username), "user_name", username).ge(ageBegin != null, "age", ageBegin).le(ageEnd != null, "age", ageEnd);
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    LambdaQueryWrapper

    功能等同于QueryWrapper,提供了Lambda表达式的语法可以避免填错列名。

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age <= ?)

    		@Test
        public void test11() {
            String username = "a";
            Integer ageBegin = null;
            Integer ageEnd = 30;
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            // ge表示大于等于,le表示小于等于
            queryWrapper.like(StringUtils.isNotBlank(username), User::getName, username).ge(ageBegin != null, User::getAge, ageBegin).le(ageEnd != null, User::getAge, ageEnd);
            List<User> list = userMapper.selectList(queryWrapper);
            list.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    LambdaUpdateWrapper

    功能等同于UpdateWrapper,提供了Lambda表达式的语法可以避免填错列名。

    执行 SQL:UPDATE t_user SET user_name=?,email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))

    		/**
         * 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
         */
        @Test
        public void test12() {
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.like(User::getName, "a").and(i -> i.gt(User::getAge, 20).or().isNull(User::getEmail));
            updateWrapper.set(User::getName, "小黑").set(User::getEmail, "abc@qq.com");
            int result = userMapper.update(null, updateWrapper);
            System.out.println("result:" + result);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    7、常用插件

    分页插件

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

    • 添加配置类 MyBatisPlusConfig
    @Configuration
    @MapperScan("cn.xx.mapper") // 扫描指定包下的mapper接口
    public class MyBatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            // 创建MyBatis-Plus的插件对象
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 添加分页插件
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 编写测试方法

    执行 SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 LIMIT ?,?

    		/**
         * 测试分页功能
         */
        @Test
        public void testPage() {
            /**
             * 第一个参数:当前页的页码
             * 第二个参数:每页显示的条数
             */
            Page<User> page = new Page<>(2, 3);
            userMapper.selectPage(page, null);
            System.out.println("当前页的数据:" + page.getRecords());
            System.out.println("当前页的页码:" + page.getCurrent());
            System.out.println("当前页的记录数:" + page.getSize());
            System.out.println("总页数:" + page.getPages());
            System.out.println("总记录数:" + page.getTotal());
            System.out.println("是否有下一页:" + page.hasNext());
            System.out.println("是否有上一页:" + page.hasPrevious());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    自定义分页

    上面是 MyBatis-Plus 提供的带有分页功能的方法,那么我们自定义的方法该如何实现分页呢?

    • UserMapper 接口中定义一个方法
    		/**
         * 通过年龄查询用户信息并分页
         * 注意:返回值必须为Page对象
         *
         * @param page MyBatis-Plus所提供的分页对象,必须处于第一个参数的位置
         * @param age
         * @return
         */
        Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 配置类型别名
    mybatis-plus:
      # 配置类型别名所对应的包(默认别名为类名,且不区分大小写)
      type-aliases-package: cn.xx.pojo
    
    • 1
    • 2
    • 3
    • UserMapper.xml 中编写SQL实现该方法
    		<!-- Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age); -->
        <select id="selectPageVo" resultType="User">
            select uid, user_name, age, email
            from t_user
            where age > #{age}
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 编写测试方法

    执行 SQL:select uid, user_name, age, email from t_user where age > ? LIMIT ?,?

    		@Test
        public void testPageVo() {
            /**
             * 第一个参数:当前页的页码
             * 第二个参数:每页显示的条数
             */
            Page<User> page = new Page<>(2, 3);
            userMapper.selectPageVo(page, 20);
            System.out.println("当前页的数据:" + page.getRecords());
            System.out.println("当前页的页码:" + page.getCurrent());
            System.out.println("当前页的记录数:" + page.getSize());
            System.out.println("总页数:" + page.getPages());
            System.out.println("总记录数:" + page.getTotal());
            System.out.println("是否有下一页:" + page.hasNext());
            System.out.println("是否有上一页:" + page.hasPrevious());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    乐观锁

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

    乐观锁的实现方式:

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

    场景

    • 一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元的话,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。
    • 此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。
    • 现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多。

    乐观锁与悲观锁

    • 上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出被修改后的价格150元,这样他会将120元存入数据库。
    • 如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也能保证最终的价格是120元。

    模拟修改冲突

    • 数据库中增加商品表
    CREATE TABLE t_product ( 
        id BIGINT(20) NOT NULL COMMENT '主键ID', 
        NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称', 
        price INT(11) DEFAULT 0 COMMENT '价格', 
        VERSION INT(11) DEFAULT 0 COMMENT '乐观锁版本号', 
        PRIMARY KEY (id) 
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 添加一条数据
    INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
    
    • 1
    • 添加一个实体类 Product
    @Data
    public class Product {
    
        private Long id;
        private String name;
        private Integer price;
        private Integer version;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 添加一个 Mapper 接口 ProductMapper
    @Repository
    public interface ProductMapper extends BaseMapper<Product> {
    }
    
    • 1
    • 2
    • 3
    • 测试方法
    		@Test
        public void testProduct01() {
            // 1、小李查询商品价格(刚开始价格是100元)
            Product productLi = productMapper.selectById(1);
            System.out.println("小李查询的商品价格:" + productLi.getPrice());
    
            // 2、小王查询商品价格(刚开始价格是100元)
            Product productWang = productMapper.selectById(1);
            System.out.println("小王查询的商品价格:" + productWang.getPrice());
    
            // 3、小李将商品价格+50元
            productLi.setPrice(productLi.getPrice() + 50);
            productMapper.updateById(productLi);
    
            // 4、小王将商品价格-30元
            productWang.setPrice(productWang.getPrice() - 30);
            int result = productMapper.updateById(productWang);
    
            // 5、老板查询商品价格
            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
    • 执行结果

    Untitled

    乐观锁实现流程

    • 数据库中添加 version 字段
    • 取出记录时,获取当前 version
    SELECT id,`name`,price,`version` FROM product WHERE id=1
    
    • 1
    • 更新记录时,将version + 1,如果 where 语句中的 version 版本不对,则更新失败
    UPDATE product SET price=price+50, `version`=`version` + 1 WHERE id=1 AND `version`=1
    
    • 1

    乐观锁解决问题

    • 实体类version字段添加 @Version 注解
    @Data
    public class Product {
    
        private Long id;
        private String name;
        private Integer price;
        @Version //标识乐观锁版本号字段
        private Integer version;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 添加乐观锁插件配置
    @Configuration
    @MapperScan("cn.xx.mapper") // 扫描指定包下的mapper接口
    public class MyBatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            // 创建MyBatis-Plus的插件对象
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 添加分页插件
            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
    • 再次执行测试方法

    小李查询商品信息:

    SELECT id,name,price,version FROM t_product WHERE id=?

    小王查询商品信息:

    SELECT id,name,price,version FROM t_product WHERE id=?

    小李修改商品价格,自动将version+1

    UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

    Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)

    小王修改商品价格,此时version已更新,条件不成立,修改失败

    UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

    Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)

    最终,小王修改失败,老板查询价格:150

    SELECT id,name,price,version FROM t_product WHERE id=?

    Untitled

    • 优化执行流程
    		@Test
        public void testProduct01() {
            // 1、小李查询商品价格
            Product productLi = productMapper.selectById(1);
            System.out.println("小李查询的商品价格:" + productLi.getPrice());
    
            // 2、小王查询商品价格
            Product productWang = productMapper.selectById(1);
            System.out.println("小王查询的商品价格:" + productWang.getPrice());
    
            // 3、小李将商品价格+50元
            productLi.setPrice(productLi.getPrice() + 50);
            productMapper.updateById(productLi);
    
            // 4、小王将商品价格-30元
            productWang.setPrice(productWang.getPrice() - 30);
            int result = productMapper.updateById(productWang);
            if (result == 0) {
                // 操作失败,重新获取version并更新
                Product productNew = productMapper.selectById(1);
                productNew.setPrice(productNew.getPrice() - 30);
                productMapper.updateById(productNew);
            }
    
            // 5、老板查询商品价格
            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
    • 28

    Untitled

    8、通用枚举

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

    • 数据库表添加字段 sex

    Untitled

    • 创建通用枚举类型
    @Getter
    public enum SexEnum {
        MALE(1, "男"), FEMALE(2, "女");
    
        @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
    • User 实体类中添加属性 sex
    @Data
    public class User {
    
        @TableId("uid")
        private Long id;
    
        @TableField("user_name")
        private String name;
    
        private Integer age;
    
        private String email;
    
        private SexEnum sex;
    
        @TableLogic
        private Integer isDeleted;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 配置扫描通用枚举
    mybatis-plus:
      # 扫描通用枚举的包
      type-enums-package: cn.xx.enums
    
    • 1
    • 2
    • 3
    • 执行测试方法
    @SpringBootTest
    public class MyBatisPlusEnumTest {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void test() {
            User user = new User();
            user.setName("admin");
            user.setAge(23);
            // 将性别设置为男
            user.setSex(SexEnum.MALE);
            int result = userMapper.insert(user);
            System.out.println("result:" + result);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    9、代码生成器

    引入依赖

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

    快速生成

    public class FastAutoGeneratorTest {
    
        public static void main(String[] args) {
            FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&userSSL=false", "root", "283619")
                    // 设置全局配置
                    .globalConfig(builder -> {
                        builder.author("xiexu") // 设置作者
                                //.enableSwagger() // 开启 swagger 模式
                                .fileOverride() // 覆盖已生成的文件
                                .outputDir("C://mybatis_plus"); // 指定输出目录
                    })
                    .packageConfig(builder -> {
                        builder.parent("com.atguigu") // 设置父包名
                                .moduleName("mybatisplus") // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "C://mybatis_plus")); // 设置mapper.Xml生成路径
                    })
                    // 配置生成策略
                    .strategyConfig(builder -> {
                        builder.addInclude("t_user") // 设置需要生成的表名
                                .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                    })
                    .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

    10、多数据源

    适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等,目前我们就来模拟一个纯粹多库的一个场景,其他场景类似

    场景说明:

    我们创建两个库,分别为:mybatis_plus(以前的库不动)与 mybatis_plus_1(新建),将 mybatis_plus 库的 product 表移动到 mybatis_plus_1 库,这样每个库一张表,通过一个测试用例分别获取用户数据与商品数据,如果获取到说明多库模拟成功

    创建数据库及表

    • 创建数据库 mybatis_plus_1 和表 product
    CREATE DATABASE `mybatis_plus_1`;
    use `mybatis_plus_1`; 
    CREATE TABLE product ( 
        id BIGINT(20) NOT NULL COMMENT '主键ID', 
        name VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称', 
        price INT(11) DEFAULT 0 COMMENT '价格', 
        version INT(11) DEFAULT 0 COMMENT '乐观锁版本号', 
        PRIMARY KEY (id) 
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 添加测试数据
    INSERT INTO product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
    
    • 1
    • 删除 mybatis_plus 库中的 product
    use mybatis_plus; 
    DROP TABLE IF EXISTS product;
    
    • 1
    • 2

    新建工程引入依赖

    自行创建一个 Spring Boot 工程并选择 MySQL 驱动及 Lombok 依赖

    • 引入 MyBaits-Plus 的依赖及多数据源的依赖
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.1version>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>dynamic-datasource-spring-boot-starterartifactId>
        <version>3.5.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    编写配置文件

    spring:
      # 配置数据源信息
      datasource:
        dynamic:
          # 设置默认的数据源或者数据源组,默认值即为master
          primary: master
          # 是否严格匹配数据源,默认false,true为未匹配到指定数据源时抛异常,false使用默认数据源
          strict: false
          datasource:
            master:
              url: jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf-8&useSSL=false
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: 283619
            slave_1:
              url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=false
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: 283619
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    创建实体类

    新建一个 User 实体类(如果数据库表名有t_前缀记得配置)

    @Data
    @TableName("t_user") // 指定所操作的表的名字
    public class User {
    
        @TableId
        private Integer uid;
    
        private String userName;
    
        private Integer age;
    
        private Integer sex;
    
        private String email;
    
        private Integer isDeleted;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    创建 Mapper 及 Service

    • 创建接口 UserMapper
    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3
    • 创建接口 ProductMapper
    @Repository
    public interface ProductMapper extends BaseMapper<Product> {
    }
    
    • 1
    • 2
    • 3
    • 创建 UserService 接口
    @DS("master") 
    public interface UserService extends IService<User> {
    }
    
    • 1
    • 2
    • 3
    • 创建 UserService 的实现类 UserServiceImpl,并指定操作的数据源
    @Service
    @DS("master") // 指定所操作的数据源,master为user表
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 创建 ProductService 接口
    public interface ProductService extends IService<Product> {
    }
    
    • 1
    • 2
    • 创建 ProductService 的实现类 ProductServiceImpl,并指定操作的数据源
    @Service
    @DS("slave_1") // 该注解可以加在类上或者方法上
    public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    编写测试方法

    记得在启动类中添加 @MapperScan() 注解

    @SpringBootApplication
    @MapperScan("cn.xx.mapper")
    public class MybatisPlusDatasourceApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MybatisPlusDatasourceApplication.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    @SpringBootTest
    class MybatisPlusDatasourceApplicationTests {
    
        @Test
        void contextLoads() {
        }
    
        @Autowired
        private UserService userService;
        @Autowired
        private ProductService productService;
    
        @Test
        public void test() {
            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
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    Untitled

    11、MyBatisX 插件

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

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

    MyBatisX 是一款基于 IDEA 的快速开发插件,为效率而生。

    安装MyBatisX插件

    Untitled

    快速生成代码

    • 新建一个 Spring Boot 项目并引入依赖
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.1version>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 配置数据源信息
    spring:
      # 配置数据源信息
      datasource:
        # 配置数据源类型
        type: com.zaxxer.hikari.HikariDataSource
        # 配置连接数据库信息
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
        username: root
        password: 283619
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 在IDEA中与数据库建立链接

    Untitled

    • 填写数据库信息并保存

    Untitled

    • 找到我们需要生成的表点击右键

    Untitled

    • 填写完信息以后下一步

    Untitled

    • 继续填写信息

    Untitled

    • 大功告成(yyds)

    Untitled

    快速生成CRUD

    MyBaitsX 可以根据我们在 Mapper 接口中输入的方法名快速帮助我们生成对应的sql语句

    Untitled

    Untitled

  • 相关阅读:
    jvs-智能bi(自助式数据分析)9.1更新内容
    基于JAVA人事管理系统计算机毕业设计源码+数据库+lw文档+系统+部署
    如何创建项目变更管理流程?
    IPv4 NAT(含Cisco配置)
    【Linux驱动开发知识点】
    腾讯云对象存储
    10CSS
    python print输出指定小数位数
    【面试刷题】——C++的特点简单说明
    Nacos Config
  • 原文地址:https://blog.csdn.net/sj15814963053/article/details/127375786