Mybatis_plus快速入门

1、入门案例

第一步:创建springboot工程

第二步:导入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhaojianhui</groupId>
    <artifactId>mybatis-plusStudy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plusStudy</name>
    <description>mybatis-plusStudy</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--        mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

  

第三步:配置文件写入对应信息

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&serverTimezone=GMT%2B8
    username: root
    password: 1314520

  

第四步:创建实体类

package com.zhaojianhui.mybatisplusstudy.pojo;

import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
public class User {

    private Long id;
    private String name;
    private Integer age;
    private String email;
}

  

第五步:创建Mapper接口,这里的泛型类型改为需要操作的实体类

package com.zhaojianhui.mybatisplusstudy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:40
 * @project springboot3_study
 */
public interface UserMapper extends BaseMapper<User> {
}

  

第六步:主程序启动类扫描对应Mapper包:

package com.zhaojianhui.mybatisplusstudy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//扫描mapper接口所在的包
@MapperScan("com.zhaojianhui.mybatisplusstudy.mapper")
public class MybatisPlusStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusStudyApplication.class, args);
    }

}

  第七步:开始测试

package com.zhaojianhui.mybatisplusstudy;

import com.zhaojianhui.mybatisplusstudy.mapper.UserMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:44
 * @project springboot3_study
 */
@SpringBootTest
public class MybatisTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelectList(){
        //通过条件构造器查询一个list,如没有条件则设置null
        List<User> list = userMapper.selectList(null);
        list.forEach(System.out::println);//输出结果

    }
}

 Tips:遇到Error creating bean with name ‘xxx‘ defined in class时,可以考虑注意springboot与mybatis-plus的版本兼容问题 

 

2、加入日志信息

配置文件中加入:

#加入日志信息
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3、测试一些增删改查

package com.zhaojianhui.mybatisplus;


import com.zhaojianhui.mybatisplus.Mapper.UserMapper;
import com.zhaojianhui.mybatisplus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:44
 * @project springboot3_study
 */
@SpringBootTest
public class Testmybatis_plus {

    @Autowired
    private UserMapper userMapper;

    @Test//测试查询方法
    public void testSelectList() {
        //通过条件构造器查询一个list,如没有条件则设置null
        List<User> list = userMapper.selectList(null);
        list.forEach(System.out::println);//输出结果

    }

    @Test//测试新增方法
    public void insertUser() {
        User user = new User(6L, "zhangdan", 26, "com.baidu.cn");
        int res = userMapper.insert(user);
        System.out.println("res:" + res);
        System.out.println("userId:" + user.getId());
    }

    @Test//测试删除方法
    public void DeleteUserById() {
        int res = userMapper.deleteById(6L);
        System.out.println("res:" + res);
    }

    @Test//测试删除方法
    public void DeleteUserByMap() {
        //map为根据条件进行删除。下面例子中表示删除name=张三并且age=23的用户
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 23);
        int res = userMapper.deleteByMap(map);
        System.out.println("res:" + res);
    }

    @Test//测试删除方法
    public void DeleteUserByBatch() {
        //通过多个id实现批量删除
//        List list=new ArrayList<>();
//        list.add(5L);
//        list.add(7L);
        List<Long> list = Arrays.asList(5L, 7L);
        int res = userMapper.deleteBatchIds(list);
        System.out.println("res:" + res);
    }

    @Test
    public void testUpdate() {//测试更新操作
        User user = new User(4L, "李四", 28, "emiallisi");
        int i = userMapper.updateById(user);
        System.out.println("res:" + i);
    }

    @Test
    public void testSelect() {//测试查询
        User user = userMapper.selectById(1L);
        //查询单个用户
        System.out.println(user);
        List<Long> lists = Arrays.asList(1L, 2L, 3L);
        //查询批量用户
        List<User> users = userMapper.selectBatchIds(lists);
        users.forEach(System.out::println);
        //根据Map进行条件查询
        Map<String,Object> map=new HashMap<>();
        map.put("name", "张三");
        map.put("age", 23);
        List<User> users1 = userMapper.selectByMap(map);
        users1.forEach(System.out::println);
        //全部查询
        List<User> users2 = userMapper.selectList(null);
        users2.forEach(System.out::println);

    }
}

 测试自定义功能:

1、在resource下新建一个mapper.xml文件,和mapper接口同名

2、userMapper接口里新建方法

package com.zhaojianhui.mybatisplusstudy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.Map;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:40
 * @project springboot3_study
 */
@Repository
public interface UserMapper extends BaseMapper<User> {
    //自定义查询功能
    Map<String,Object> selectMapById(Long id);
}

3、mapper.xml中新建查询sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhaojianhui.mybatisplusstudy.mapper.UserMapper">
    <!--    Map<String,Object> selectMapById(Long id);-->
    <select id="selectMapById" resultType="java.util.Map">
        select id, name, age, email
        from user
        where id = #{id}
    </select>

</mapper>

4、测试结果

System.out.println("*******测试自定义查询*********");
        Map<String, Object> map = userMapper.selectMapById(1L);
        System.out.println(map);

 

通用Service接口:

1、首先创建UserService接口

package com.zhaojianhui.mybatisplusstudy.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.zhaojianhui.mybatisplusstudy.pojo.User;

/**
 * @author zhaojianhui
 * @date 2023-07-01-19:24
 * @project springboot3_study
 */
public interface UserService extends IService<User> {
}

2、创建其对应实现类

package com.zhaojianhui.mybatisplusstudy.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaojianhui.mybatisplusstudy.mapper.UserMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;
import com.zhaojianhui.mybatisplusstudy.service.UserService;
import org.springframework.stereotype.Service;

/**
 * @author zhaojianhui
 * @date 2023-07-01-19:25
 * @project springboot3_study
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

3、进行测试

package com.zhaojianhui.mybatisplusstudy;

import com.zhaojianhui.mybatisplusstudy.pojo.User;
import com.zhaojianhui.mybatisplusstudy.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaojianhui
 * @date 2023-07-01-19:30
 * @project springboot3_study
 */
@SpringBootTest
public class Mybatis_plus_serviceTest {

    @Autowired
    private UserService userService;


    @Test
    public void testGetCount() {
        //查询总数
        long count = userService.count();
        System.out.println("总记录数:" + count);
    }
    @Test
    public void addBatch() {
        //批量添加
        List<User> list=new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            User user=new User();
            user.setName("zzz"+i);
            user.setAge(20+i);
            list.add(user);
            
        }
        boolean b = userService.saveBatch(list);
        System.out.println(b);
    }
}

  

常用注解:

1、@TableName:实体名对应数据库表名

package com.zhaojianhui.mybatisplusstudy.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
@TableName("user")//当实体名和数据库表名不一致时,可以进行指定,以数据库表名为准
public class User {

    private Long id;
    private String name;
    private Integer age;
    private String email;
}

2、全局配置表前缀:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  #设置全局配置
  global-config:
    db-config:
      #实体类所有的名字对应的表明都加上了t_的前缀
      table-prefix: t_
    #设置主键递增策略
     id-type: auto

3、@TableId:主键字段对应数据库字段

package com.zhaojianhui.mybatisplusstudy.pojo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
@TableName("user")//当实体名和数据库表名不一致时,可以进行指定,以数据库表名为准
public class User {
    @TableId//将属性对应的字段指定为主键,适用于表字段没有id时或者id不是主键时
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
package com.zhaojianhui.mybatisplusstudy.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
@TableName("user")//当实体名和数据库表名不一致时,可以进行指定,以数据库表名为准
public class User {
    @TableId(value = "uid",type = IdType.AUTO)//value属性将id属性对应为数据库的uid字段(其中uid为主键),type属性设置主键生成策略
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

 

@TableField:普通属性字段对应数据库字段
package com.zhaojianhui.mybatisplusstudy.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
@TableName("user")//当实体名和数据库表名不一致时,可以进行指定,以数据库表名为准
public class User {
    @TableId(value = "uid",type = IdType.AUTO)//value属性将id属性对应为数据库的uid字段(其中uid为主键),type属性设置主键生成策略
    private Long id;
    @TableField("user_name")//设置普通字段的对应关系,@TableId是设置主键对应关系
    private String name;
    private Integer age;
    private String email;
    @TableLogic
    private Integer isDeleted;
}

 

@TableLogic:逻辑删除
package com.zhaojianhui.mybatisplusstudy.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhaojianhui
 * @date 2023-06-29-19:16
 * @project springboot3_study
 */
@Data
@TableName("user")//当实体名和数据库表名不一致时,可以进行指定,以数据库表名为准
public class User {
    //@TableId(value = "id",type = IdType.AUTO)//value属性将id属性对应为数据库的uid字段(其中uid为主键),type属性设置主键生成策略
    private Long id;
    //@TableField("user_name")//设置普通字段的对应关系,@TableId是设置主键对应关系
    private String name;
    private Integer age;
    private String email;
    //逻辑删除,隐藏了
    @TableLogic
    private Integer isDeleted;
}

  

  @Test
    public void testDelete(){
        List<Long> list = Arrays.asList(1L, 2L);
        int res = userMapper.deleteBatchIds(list);
        System.out.println(res);
    }

 

条件构造器:

package com.zhaojianhui.mybatisplusstudy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaojianhui.mybatisplusstudy.mapper.UserMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author zhaojianhui
 * @date 2023-07-02-14:17
 * @project springboot3_study
 */
@SpringBootTest
public class MybatisPlusWapperTest {
    @Autowired
    private UserMapper userMapper;

    //组装查询条件
    @Test
    public void test1() {
        //用户名包含a且年龄在20-30,邮箱不为空
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //第一个参数是数据库中表的字段
        queryWrapper.like("name", "a").
                between("age", 20, 30).isNotNull("email");
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }

    @Test
    public void test2() {
        //查询用户信息,按照年龄降序,如年龄相同,则按照Id升序
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("age").orderByAsc("id");
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }

    @Test
    //封装删除功能
    public void test3() {
        //删除邮箱为Null的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("email");
        int res = userMapper.delete(queryWrapper);
        System.out.println("res:" + res);
    }
    @Test
    //封装修改功能
    public void test4() {
        //将年龄大于20并且名字包含a或邮箱为null的用户信息修改
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //gt:大于
        queryWrapper.gt("age",20).like("name","a").
                or().isNull("email");
        User user=new User();
        user.setName("小明");
        user.setEmail("test@Email");
        int res = userMapper.update(user,queryWrapper);
        System.out.println("res:" + res);
    }
}

 条件构造器的优先级:

    @Test
    //封装修改功能
    public void test5() {
        //优先级
        //将年龄大于20并且(名字包含a或邮箱为null)的用户信息修改
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //gt:大于
        //lambda表达式中的条件优先执行
        queryWrapper.like("name", "a").
                and(i -> i.gt("age", 20).or().isNull("email"));
        User user = new User();
        user.setName("小明1");
        user.setEmail("test@Email");
        int res = userMapper.update(user, queryWrapper);
        System.out.println("res:" + res);
    }

  组装select子句:

 @Test
    public void test6() {
        //查询用户的部分信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name", "age");
        List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
        maps.forEach(System.out::println);

    }

  组装子查询:

    @Test
    public void test7() {
        //查询id<=100的用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //构造子查询语句
        queryWrapper.inSql("id","select id from user where id<=100");
        List<User> list = userMapper.selectList(queryWrapper);
        //List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
        list.forEach(System.out::println);

    }

  使用updateWrapper实现修改功能:

   @Test
    public void test8() {
        //将名字包含a并且(年龄大于20或邮箱为null)的用户信息修改
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.like("name", "a").and(i ->
                i.gt("age", 20).or().isNull("email"));
        updateWrapper.set("name", "小白").set("email", "abc");
        int res = userMapper.update(null, updateWrapper);
        System.out.println("res:" + res);

    }

  组装查询条件:

 @Test
    public void test9() {
        String name = "";
        Integer lowage = 10;
        Integer underage = 28;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        //ge:>=
        if (lowage != null) {
            queryWrapper.ge("age", lowage);

        }
        //le:<=
        if (underage != null) {
            queryWrapper.le("age", underage);

        }
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);


    }

  

通用枚举:

1、新建枚举类

package com.zhaojianhui.mybatisplusstudy.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

/**
 * @author zhaojianhui
 * @date 2023-07-02-21:03
 * @project springboot3_study
 */
@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;
    }
}

 2、枚举类加注解@EnumValue

3、配置文件进行配置

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&serverTimezone=GMT%2B8
    username: root
    password: 1314520
#加入日志信息
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  #设置全局配置
  global-config:
    db-config:
      #实体类所有的名字对应的表明都加上了t_的前缀
      table-prefix: t_
      #设置主键递增策略
      id-type: auto

  #配置类型别名所对应的包
  type-aliases-package: com.zhaojianhui.mybatisplusstudy.pojo
  #扫描通用枚举包
  type-enums-package: com.zhaojianhui.mybatisplusstudy.enums

  4、测试

package com.zhaojianhui.mybatisplusstudy;

import com.zhaojianhui.mybatisplusstudy.enums.SexEnum;
import com.zhaojianhui.mybatisplusstudy.mapper.UserMapper;
import com.zhaojianhui.mybatisplusstudy.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author zhaojianhui
 * @date 2023-07-02-21:06
 * @project springboot3_study
 */
@SpringBootTest
public class TestEnum {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test() {
        User user = new User();
        user.setId(9L);
        user.setName("admin");
        user.setAge(33);
        user.setSex(SexEnum.MALE);
        int res = userMapper.insert(user);
        System.out.println("res:" + res);
    }

}

  

代码生成器:

1、引入依赖

<!--        代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

2、填写代码生成器

package com.zhaojianhui.mybatisplusstudy;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.sql.Types;
import java.util.Collections;

/**
 * @author zhaojianhui
 * @date 2023-07-02-21:27
 * @project springboot3_study
 */
public class AutoGeneratorTest {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8", "root", "1314520")
                .globalConfig(builder -> {
                    builder.author("zhaojianhui") // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("F://testMybatisPlusGen"); // 指定输出目录
                })
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        // 自定义类型转换
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);

                }))
                .packageConfig(builder -> {
                    builder.parent("com.zhaojianhui.mybatisplus") // 设置父包名
                            .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "F://testMybatisPlusGen")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

  

模拟多数据源:

使用场景:

1、添加依赖

<!--        配置多数据源-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

2、添加配置信息

spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: 52213200
        slave_1:
          url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: 52213200

3、在service实现类上指定要操作的数据源

package com.zhaojianhui.mybatisplus.Service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaojianhui.mybatisplus.Mapper.UserMapper;
import com.zhaojianhui.mybatisplus.Service.UserService;
import com.zhaojianhui.mybatisplus.pojo.User;
import org.springframework.stereotype.Service;

@Service
@DS("master")//指定操作的数据源
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

 

 

4、测试

package com.zhaojianhui.mybatisplus;

import com.zhaojianhui.mybatisplus.Service.ProductService;
import com.zhaojianhui.mybatisplus.Service.UserService;
import com.zhaojianhui.mybatisplus.pojo.Product;
import com.zhaojianhui.mybatisplus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestMultiDatasource {

    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Test
    public void test(){
        User user = userService.getById(1L);
        Product product = productService.getById(1);
        System.out.println(user);
        System.out.println("*************");
        System.out.println(product);
    }
}

  

 MybatisPlusX:
IDEA的settings中下载MybatisX插件,然后打勾启用。重启idea生效
然后如下图:

 

 

 

点击finish即可。

回到mapper接口:

 

查为select。增为insert,删为delete...选择mybatisX提供的方法,然后alt+enter补充接口函数和mapper对应sql语句

 

 通过此可以快速进行单表增删改查。

posted @ 2023-07-03 14:43  zhaojianhui  阅读(27)  评论(0编辑  收藏  举报