SpringBoot 整合MyBatis-Plus 详细教程,配置多数据源并支持事务,附带代码生成器使用教程

  • Post author:
  • Post category:其他




SpringBoot 整合MyBatis-Plus 详细教程,配置多数据源并支持事务,附带代码生成器使用教程

一.在pom.xml加入依赖,如下

<!-- MySQL驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- mybatisPlus 核心库 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1</version>
</dependency>
<!-- dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.1.0</version>
</dependency>
<!-- mybatisPlus 代码生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.1.tmp</version>
</dependency>
<!-- mybatisPlus Velocity 模版引擎 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>
<!-- mybatisPlus Freemarker 模版引擎 -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.29</version>
</dependency>

二.在application.yml配置多数据源,mybatis-plus相关配置

spring:
  # 配置数据源
  datasource:
    dynamic:
      primary: db1 # 设置默认的数据源或者数据源组,默认值即为master
      datasource:
        db1:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx:3306/mybatisplus_demo?useUnicode=true&characterEncoding=utf-8
          username: xxx
          password: xxx
          # hikari
          hikari:
            connection-test-query: SELECT 1
            ## 最小空闲连接数量
            minimum-idle: 5
            ## 连接池最大连接数,默认是10
            maximum-pool-size: 15
            ## 连接池名称
            pool-name: MyHikariCPOfMaster
            ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认180000030分钟
            max-lifetime: 1800000
            ## 数据库连接超时时间,默认30秒,即30000
            connection-timeout: 20000
            ## 空闲连接存活最大时间,默认60000010分钟)
            idle-timeout: 180000
            ## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
            auto-commit: true
        db2:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx:3306/mybatisplus_demo?useUnicode=true&characterEncoding=utf-8
          username: xxx
          password: xxx
          # hikari
          hikari:
            connection-test-query: SELECT 1
            ## 最小空闲连接数量
            minimum-idle: 5
            ## 连接池最大连接数,默认是10
            maximum-pool-size: 15
            ## 连接池名称
            pool-name: MyHikariCPOfMaster
            ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认180000030分钟
            max-lifetime: 1800000
            ## 数据库连接超时时间,默认30秒,即30000
            connection-timeout: 20000
            ## 空闲连接存活最大时间,默认60000010分钟)
            idle-timeout: 180000
            ## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
            auto-commit: true

# mybatis-plus相关配置
mybatis-plus:
  # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:com/luoyu/mybatisplus/mapper/xml/*.xml
  # 以下配置均有默认值,可以不设置
  global-config:
    db-config:
      #主键类型  auto:"数据库ID自增" 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
      id-type: auto
      #字段策略 IGNORED:"忽略判断"  NOT_NULL:"非 NULL 判断")  NOT_EMPTY:"非空判断"
      field-strategy: NOT_EMPTY
      #数据库类型
      db-type: MYSQL
  configuration:
    # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
    map-underscore-to-camel-case: true
    # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
    call-setters-on-nulls: true
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

三.创建数据库db1,创建表User,插入测试数据,查看测试数据;创建数据库db2,创建表Task,插入测试数据,查看测试数据

User表

CREATE DATABASE mybatisplus_demo;

use mybatisplus_demo;

CREATE TABLE user
(
    id INT NOT NULL COMMENT '主键ID',
    name VARCHAR(50) NULL DEFAULT NULL COMMENT '姓名',
    age INT NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
)CHARSET=utf8 ENGINE=InnoDB COMMENT '用户表';

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

select * from user;

Task表

CREATE DATABASE mybatisplus_demo;

use mybatisplus_demo;

CREATE TABLE task
(
    id INT NOT NULL COMMENT '主键ID',
    name VARCHAR(50) NULL DEFAULT NULL COMMENT '姓名',
    age INT NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
)CHARSET=utf8 ENGINE=InnoDB COMMENT '任务表';

INSERT INTO task (id, name, age, email) VALUES
(6, '李白', 18, 'test1@baomidou.com'),
(7, '露娜', 20, 'test2@baomidou.com'),
(8, '韩信', 28, 'test3@baomidou.com'),
(9, '橘右京', 21, 'test4@baomidou.com'),
(10, '百里玄刺', 24, 'test5@baomidou.com');

select * from task;

四. 创建MybatisPlus配置类,MybatisPlusConfig,主要是配置一些插件的使用

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】,设置 dev test 环境开启
     */
//    @Bean
//    @Profile({"dev", "qa"})
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//        performanceInterceptor.setMaxTime(1000);
//        performanceInterceptor.setFormat(true);
//        return performanceInterceptor;
//    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
         paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
         paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

五. 踩坑!!!如果xml文件没有放在resources目录下的话,需要在pom.xml文件的标签里面新增以下配置,否则就算在application.yml文件配置了扫描xml文件的路径也没用,小坑!!!

<resources>
    <resource>
        <directory>src/main/java</directory>
        <!-- src/main/java下的指定资源放行 -->
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

六.在启动类MybatisplusApplication新增@MapperScan注解,里面写入生成的文件中的mapper存放的路径,用于扫描mapper文件。到此springboot2.2.5 整合MyBatis-Plus3.3.1 完毕,直接在mapper文件写sql语句,在service文件调用即可。

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

@MapperScan("com.luoyu.mybatisplus.mapper")
@SpringBootApplication
public class MybatisplusApplication {

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

}

七. 新增自定义的sql方法,编写IUserService,UserServiceImpl,UserMapper,UserMapper.xml用于操作数据源db1;ITaskService,TaskServiceImpl,TaskMapper,TaskMapper.xml用于操作数据源db2,分别如下

注:

在UserServiceImpl,TaskServiceImpl中,@DS()注解代表指定各自的数据源,@Transactional注解代表开启Spring事务。

数据源db1,IUserService

import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyu.mybatisplus.entity.User;


public interface IUserService extends IService<User> {

   
    User selectByName(String name);

   
    int updateName(int id, String name);

}

UserServiceImpl

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyu.mybatisplus.entity.User;
import com.luoyu.mybatisplus.mapper.UserMapper;
import com.luoyu.mybatisplus.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@DS("db1")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    
    @Override
    public User selectByName(String name) {
        return userMapper.selectByName(name);
    }

   
    @Transactional
    @Override
    public int updateName(int id, String name) {
        int n = userMapper.updateName(id, name);
        // 此处报错事务回滚
        int i = 1/0;
        return n;
    }
}

UserMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.luoyu.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Param;


public interface UserMapper extends BaseMapper<User> {

    
    User selectByName(String name);

    
    int updateName(@Param("id") int id, @Param("name") String name);

}

UserMapper.xml

<?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.luoyu.mybatisplus.mapper.UserMapper">

    <select id="selectByName" parameterType="string" resultType="com.luoyu.mybatisplus.entity.User">
        select * from user where name = #{name};
    </select>

    <update id="updateName">
        update user set name = #{name} where id = #{id};
    </update>

</mapper>

数据源db2,ITaskService

import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyu.mybatisplus.entity.Task;
import com.luoyu.mybatisplus.entity.User;


public interface ITaskService extends IService<Task> {

    
    Task selectByName(String name);

   
    int updateName(int id, String name);

}

TaskServiceImpl

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyu.mybatisplus.entity.Task;
import com.luoyu.mybatisplus.entity.User;
import com.luoyu.mybatisplus.mapper.TaskMapper;
import com.luoyu.mybatisplus.mapper.UserMapper;
import com.luoyu.mybatisplus.service.ITaskService;
import com.luoyu.mybatisplus.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@DS("db2")
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Resource
    private TaskMapper taskMapper;

   
    @Override
    public Task selectByName(String name) {
        return taskMapper.selectByName(name);
    }

   
    @Transactional
    @Override
    public int updateName(int id, String name) {
        return taskMapper.updateName(id, name);
    }
}

TaskMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.luoyu.mybatisplus.entity.Task;
import org.apache.ibatis.annotations.Param;


public interface TaskMapper extends BaseMapper<Task> {

   
    Task selectByName(String name);

  
    int updateName(@Param("id") int id, @Param("name") String name);

}

TaskMapper.xml

<?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.luoyu.mybatisplus.mapper.TaskMapper">

    <select id="selectByName" parameterType="string" resultType="com.luoyu.mybatisplus.entity.Task">
        select * from task where name = #{name};
    </select>

    <update id="updateName">
        update task set name = #{name} where id = #{id};
    </update>
    
</mapper>

八. 编写单元测试类,MybatisplusApplicationTests,并进行测试,只列举了部分方法

import com.luoyu.mybatisplus.entity.Task;
import com.luoyu.mybatisplus.entity.User;
import com.luoyu.mybatisplus.service.ITaskService;
import com.luoyu.mybatisplus.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@Slf4j
// 获取启动类,加载配置,确定装载 Spring 程序的装载方法,它回去寻找 主配置启动类(被 @SpringBootApplication 注解的)
@SpringBootTest
class MybatisplusApplicationTests {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private ITaskService iTaskService;

    @Test
    void selectApiTest() {
        log.info("使用MP提供的CRUD");
        User user = iUserService.getById("1");
        log.info(user.toString());
    }

    @Test
    void selectDb1Test() {
        // 验证多数据源db1
        log.info("使用自定义的方法,查看db1");
        User user = iUserService.selectByName("Jack");
        log.info(user.toString());
    }

    @Test
    void selectDb2Test() {
        // 验证多数据源db2
        log.info("使用自定义的方法,查看db2");
        Task task = iTaskService.selectByName("韩信");
        log.info(task.toString());
    }

    @Test
    void updateDb1Test() {
        // 验证事务
        iUserService.updateName(1, "改名啦");
    }

    @BeforeEach
    void testBefore(){
        log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

    @AfterEach
    void testAfter(){
        log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

}



版权声明:本文为ChenJin_2原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。