• MyBatis-Plus(二)- 进阶使用


    一、条件构造器和常用接口

    1. wapper介绍

    在这里插入图片描述

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

    2. QueryWrapper

    (1)组装查询条件

    @Test 
    public void test01() { 
    	// 查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息 
    	// SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (username LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL) 
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>(); 
    	queryWrapper.like("username", "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
    • 11

    (2)组装排序条件

    @Test 
    public void test02() { 
    	// 按年龄降序查询用户,如果年龄相同则按id升序排列 
    	// SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,id ASC 
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>(); 
    	queryWrapper .orderByDesc("age") 
    				 .orderByAsc("id"); 
    	List<User> users = userMapper.selectList(queryWrapper); 
    	users.forEach(System.out::println); 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    (3)组装删除条件

    @Test 
    public void test03() { 
    	// 删除email为空的用户 / /DELETE FROM t_user WHERE (email IS NULL) 
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>(); 
    	queryWrapper.isNull("email"); 
    	// 条件构造器也可以构建删除语句的条件 
    	int result = userMapper.delete(queryWrapper); 
    	System.out.println("受影响的行数:" + result); 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (4)条件的优先级

    @Test
    public void test04(){
        // 将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
        //UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (age > ? AND user_name LIKE ? OR email IS NULL)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("age", 20)
                 .like("user_name", "a")
                 .or()
                 .isNull("email");
        User user = new User();
        user.setName("小明");
        user.setEmail("test@atguigu.com");
        int result = userMapper.update(user, queryWrapper);
        System.out.println("result:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    @Test
    public void test05(){
        // 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
        // lambda中的条件优先执行
        // UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name", "a")
                    .and(i->i.gt("age",20).or().isNull("email"));
        User user = new User();
        user.setName("小红");
        user.setEmail("test@atguigu.com");
        int result = userMapper.update(user, queryWrapper);
        System.out.println("result:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    (5)组装select子句

    @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

    (6)实现子查询

    @Test
    public void test07(){
        // 查询id小于等于100的用户信息
        // SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (uid IN (select id from t_user2 where id <= 100))
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("uid", "select id from t_user2 where id <= 100");
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3. UpdateWrapper

    @Test
    public void test08(){
       // 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
       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:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4. condition

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

    (1)方式一:

    @Test
    public void test09(){
       // 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 <= ?)
       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){
           queryWrapper.ge("age", ageBegin);
       }
       if(ageEnd != null){
           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

    (2)方式二:

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

    @Test
    public void test10(){
        String username = "a";
        Integer ageBegin = null;
        Integer ageEnd = 30;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        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

    5. LambdaQueryWrapper

    LambdaQueryWrapper代替QueryWrapper
    避免使用字符串表示字段,防止运行时错误

    @Test
    public void test11(){
         //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 <= ?)
         String username = "a";
         Integer ageBegin = null;
         Integer ageEnd = 30;
         LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
         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
    • 12
    • 13

    6. LambdaUpdateWrapper

    LambdaUpdateWrapper代替UpdateWrapper
    避免使用字符串表示字段,防止运行时错误

    @Test
    public void test12(){
        // 将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
        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@atguigu.com");
        int result = userMapper.update(null, updateWrapper);
        System.out.println("result:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    二、插件

    1. 分页插件

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

    (1)添加配置类

    @Configuration
    // 扫描mapper接口所在的包,可以将之前主类中的注解移到此处
    @MapperScan("com.atguigu.mybatisplus.mapper")
    public class MyBatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            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

    (2)测试

    @Test 
    public void testPage() { 
    	// 设置分页参数 
    	Page<User> page = new Page<>(1, 5); 
    	userMapper.selectPage(page, null); 
    	// 获取分页数据 
    	List<User> list = page.getRecords(); 
    	list.forEach(System.out::println); 
    	System.out.println("当前页:"+page.getCurrent()); 
    	System.out.println("每页显示的条数:"+page.getSize()); 
    	System.out.println("总记录数:"+page.getTotal()); 
    	System.out.println("总页数:"+page.getPages()); 
    	System.out.println("是否有上一页:"+page.hasPrevious()); 
    	System.out.println("是否有下一页:"+page.hasNext()); 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    ==>  Preparing: SELECT COUNT(*) AS total FROM user
    ==> Parameters: 
    <==    Columns: total
    <==        Row: 6
    <==      Total: 1
    ==>  Preparing: SELECT id,name,age,email FROM user LIMIT ?
    ==> Parameters: 5(Long)
    <==    Columns: id, name, age, email
    <==        Row: 1, Jone, 18, test1@baomidou.com
    <==        Row: 2, Jack, 20, test2@baomidou.com
    <==        Row: 3, Tom, 28, test3@baomidou.com
    <==        Row: 4, Sandy, 21, test4@baomidou.com
    <==        Row: 5, Billie, 24, test5@baomidou.com
    <==      Total: 5
    Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b8280e6]
    User(id=1, name=Jone, age=18, email=test1@baomidou.com)
    User(id=2, name=Jack, age=20, email=test2@baomidou.com)
    User(id=3, name=Tom, age=28, email=test3@baomidou.com)
    User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
    User(id=5, name=Billie, age=24, email=test5@baomidou.com)
    当前页:1
    每页显示的条数:5
    总记录数:6
    总页数:2
    是否有上一页:false
    是否有下一页:true
    
    • 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

    2. xml自定义分页

    (1)UserMapper中定义接口方法

    @Repository
    public interface UserMapper extends BaseMapper<User> {
    
        /**
         * 通过年龄查询用户信息并分页
         * @param page MyBatis-Plus所提供的分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
         * @param age
         * @return
         */
        Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (2)UserMapper.xml中编写SQL

    <mapper namespace="com.atguigu.mybatisplus.mapper.UserMapper">
    
    	<!--SQL片段,记录基础字段--> 
    	<sql id="BaseColumns">id,username,age,email</sql>
    	
        <!--Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);-->
        <select id="selectPageVo" resultType="User">
            select <include refid="BaseColumns"></include> from t_user where age > #{age}
        </select>
    
    </mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (3)测试

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

    3. 乐观锁

    (1)场景

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

    (2)乐观锁与悲观锁

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

    (3)模拟修改冲突

    数据库中增加商品表:

    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
    • 8

    添加数据:

    INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
    
    • 1

    添加实体:

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

    添加mapper:

    public interface ProductMapper extends BaseMapper<Product> { 
    
    }
    
    • 1
    • 2
    • 3

    测试:

    @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);
        int result1 = productMapper.updateById(productLi);
        System.out.println("小李修改结果:" + result1);
        // 4.小王将商品价格-30,存入了数据库
        productWang.setPrice(productWang.getPrice()-30);
        int result2 = productMapper.updateById(productWang);
        System.out.println("小王修改结果:" + result2);
        
        // 老板查询商品价格
        Product productLaoban = productMapper.selectById(1);
        // 价格覆盖,老板查询的商品价格:70
        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

    (4)乐观锁实现流程

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

    (5)Mybatis-Plus实现乐观锁

    修改实体类:

    @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

    添加乐观锁插件配置:

    @Configuration
    // 扫描mapper接口所在的包
    @MapperScan("com.atguigu.mybatisplus.mapper")
    public class MyBatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            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

    优化流程:

    @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);
        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

    小李查询商品信息:
    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=?

    三、通用枚举

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

    (1)数据库表添加字段sex

    在这里插入图片描述
    (2)创建通用枚举类型

    @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
    • 14

    (3)配置扫描通用枚举

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      # 设置MyBatis-Plus的全局配置
      global-config:
        db-config:
          # 设置实体类所对应的表的统一前缀
          table-prefix: t_
          # 设置统一的主键生成策略
          id-type: auto
      # 扫描通用枚举的包
      type-enums-package: com.atguigu.mybatisplus.enums
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (4)测试

    @Test
    public void test(){
        User user = new User();
        user.setName("admin");
        user.setAge(33);
        // 设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库
        user.setSex(SexEnum.MALE);
        // INSERT INTO t_user ( username, age, sex ) VALUES ( ?, ?, ? ) // Parameters: Enum(String), 20(Integer), 1(Integer)
        int result = userMapper.insert(user);
        System.out.println("result:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    四、代码生成器

    1. 引入依赖

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.5.1</version>
    </dependency>
    
    <!--使用Freemarker引擎模板-->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.31</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2. 快速生成

    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", "root")
                    .globalConfig(builder -> {
                        builder.author("lwk") // 设置作者
                                //.enableSwagger() // 开启 swagger 模式
                                .fileOverride() // 覆盖已生成文件
                                .outputDir("D://mybatis_plus"); // 指定输出目录
                    })
                    .packageConfig(builder -> {
                        builder.parent("com.lwk") // 设置父包名
                                .moduleName("mybatisplus") // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus")); // 设置mapperXml生成路径
                    })
                    .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

    五、多数据源

    适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等
    目前我们就来模拟一个纯粹多库的一个场景,其他场景类似
    场景说明:
    我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例分别获取用户数据与商品数据,如果获取到说明多库模拟成功

    1. 创建数据库及表

    创建数据库mybatis_plus_1和表product

    CREATE DATABASE `mybatis_plus_1` /* DEFAULT CHARACTER SET utf8mb4 */;
    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
    • 10

    添加测试数据
    INSERT INTO product (id, NAME, price) VALUES (1, ‘外星人笔记本’, 100);
    删除mybatis_plus库product表
    use mybatis_plus;
    DROP TABLE IF EXISTS product;

    2. 引入依赖

    <dependency>
    	<groupId>com.baomidou</groupId>
    	<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    	<version>3.5.0</version>
    </dependency>	
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3. 配置多数据源

    说明:注释掉之前的数据库连接,添加新配置

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

    4. 创建用户service

    public interface UserService extends IService<User> {
    }
    
    • 1
    • 2
    @Service
    @DS("master") // 指定所操作的数据源
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    }
    
    • 1
    • 2
    • 3
    • 4

    5. 创建商品service

    public interface ProductService extends IService<Product> {
    }
    
    • 1
    • 2
    @Service
    @DS("slave_1")
    public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    }
    
    • 1
    • 2
    • 3
    • 4

    6. 测试

    @SpringBootTest
    class MybatisPlusDatasourceApplicationTests {
    
    	@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

    结果:
    1、都能顺利获取对象,则测试成功
    2、如果我们实现读写分离,将写操作方法加上主库数据源,读操作方法加上从库数据源,自动切换,就能实现读写分离

  • 相关阅读:
    【LeetCode】Day187-分割回文串
    编程入门(五)【Visual Studio Code安装与C/C++语言运行】
    Asp.Net Core 实现分片下载的最简单方式
    程序员工具
    UG NX二次开发(C#)-采用NXOpen完成对象的合并操作
    NP管理器 NPManager v3.0.49 安卓APK逆向反编译工具
    【HTML实战】把爱心代码放在自己的网站上是一种什么体验?
    Spring Data Elasticsearch介绍(七)
    码蹄杯语言基础:选择结构(C语言)
    【计算机网络】 7、websocket 概念、sdk、实现
  • 原文地址:https://blog.csdn.net/qq_36602071/article/details/126197822