SpringBoot2.0整合Mybatis-Plus多数据源

文章目录

    • 一、pom依赖
    • 二、application.yml多数据源配置
    • 三、持久层
      • 3.1. UserMapper 接口
      • 3.2. 接口映射UserMapper.xml(可以不写)
    • 四、逻辑处理层
      • 4.1. IUserService 接口
      • 4.2. 接口实现类IUserServiceImpl
    • 五、通用返回对象封装
    • 六、测试UserController
    • 七、启动类加扫描mapper注解
    • 八、数据库脚本
      • 8.1. masterdb.sql
      • 8.2. slavedb.sql
    • 九、测试验证
      • 9.1. 主库新增用户
      • 9.2. 从库新增用户
      • 9.3. 获取主库用户列表
      • 9.4. 获取从库用户列表
      • 9.5.

一、pom依赖

需要引入与SpringBoot整合好的动态数据源依赖,以及mybatis-plus相关依赖包

       
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            com.baomidou
            dynamic-datasource-spring-boot-starter
            ${dynamic-datasource.version}
        
        
        
            org.projectlombok
            lombok
            1.18.10
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.2.0
        
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
            runtime
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

二、application.yml多数据源配置

直接复制到你的项目中即可,通过primary来指定默认数据源,配置如下:

server:
  port: 80

# 数据源配置
spring:
  datasource:
    dynamic:
      primary: master   #设置默认的数据源
      datasource:
        master:
          username: root
          password: root
          url: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
          driver-class-name: com.mysql.cj.jdbc.Driver
        # 从数据源配置
        slave:
          username: root
          password: root
          url: jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
          driver-class-name: com.mysql.cj.jdbc.Driver
      mp-enabled: true


# 数据源加载日志
logging:
  level:
    com.xkcoding.multi.datasource.mybatis: debug

三、持久层

3.1. UserMapper 接口

public interface UserMapper extends BaseMapper {
}

3.2. 接口映射UserMapper.xml(可以不写)





四、逻辑处理层

4.1. IUserService 接口

import com.baomidou.mybatisplus.extension.service.IService;
import com.gblfy.springboot.mybatisplus.entity.User;

import java.util.List;

public interface IUserService extends IService {
    /**
     * 往从库中插入数据
     *
     * @param user
     */
    Integer addUserToSlave(User user);


    /**
     * 主库插入
     *
     * @param user
     */
    Integer addUserToMaster(User user);

    /**
     * 获取主库用户列表
     *
     * @return
     */
    List findMasterUserList();

    /**
     * 获取从库用户列表
     *
     * @return
     */
    List findSlaveUserList();
}

4.2. 接口实现类IUserServiceImpl

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

import java.util.List;

/**
 * @author gblfy
 * @ClassNme IUserServiceImpl
 * @Description TODO
 * @Date 2019/12/8 10:21
 * @version1.0
 */
@Service
@DS("master")
public class IUserServiceImpl extends ServiceImpl implements IUserService {

    @DS("slave")
    @Override
    public Integer addUserToSlave(User user) {
        return null;
    }

    @Override
    public Integer addUserToMaster(User user) {
        return null;
    }

    @Override
    public List findMasterUserList() {
        return null;
    }

    @DS("slave")
    @Override
    public List findSlaveUserList() {
        return null;
    }
}

五、通用返回对象封装

/**
 * 公共返回实体类
 */
@Data
public class ResultObject {

    /**
     * 可为数组或字符串等,可记录错误信息或正常返回的相关信息
     */
    private Object message;

    /**
     * 返回码  200代表正常  1代表失败
     */
    private int code;

    private Object result;

}

六、测试UserController

import com.gblfy.springboot.mybatisplus.entity.User;
import com.gblfy.springboot.mybatisplus.service.IUserService;
import com.gblfy.springboot.mybatisplus.utils.ResultObject;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: gblfy
 * @desc: 用户控制层
 * @date: 2019/12/8 10:25
 */
@RestController
@RequestMapping("/user")
@Data
public class UserController {

    @Autowired
    private IUserService userService;


    /**
     * 主库新增用户
     * @param user
     * @return
     */
    @GetMapping("addUserToMaster")
    public Object addUserToMaster(User user){
        ResultObject resultObject = new ResultObject();
        try {
            User userMaster = User.builder()
                    .name(user.getName())
                    .age(user.getAge())
                    .email(user.getEmail())
                    .build();
            resultObject.setResult(userService.addUserToMaster(userMaster));
            resultObject.setCode(200);
            resultObject.setMessage("主库新增用户成功");
        } catch (Exception e) {
            resultObject.setCode(-1);
            resultObject.setMessage("主库新增用户失败");
            e.printStackTrace();
        }
        return resultObject;
    }

    /**
     * 从库新增用户
     * @param user
     * @return
     */
    @GetMapping("addUserToSlave")
    public Object addUserToSlave(User user){
        ResultObject resultObject = new ResultObject();
        try {
            User userSlave = User.builder()
                    .name(user.getName())
                    .age(user.getAge())
                    .email(user.getEmail())
                    .build();
            resultObject.setResult(userService.addUserToSlave(userSlave));
            resultObject.setCode(200);
            resultObject.setMessage("从库新增用户成功");
        } catch (Exception e) {
            resultObject.setCode(-1);
            resultObject.setMessage("从库新增用户失败");
            e.printStackTrace();
        }
        return resultObject;
    }

    /**
     * 获取主库用户列表
     * @return
     */
    @RequestMapping("findMasterUserList")
    public Object findMasterUserList(){
        ResultObject resultObject = new ResultObject();
        try {
            resultObject.setResult(userService.findMasterUserList());
            resultObject.setCode(200);
            resultObject.setMessage("获取主库用户列表成功");
        } catch (Exception e) {
            resultObject.setCode(-1);
            resultObject.setMessage("获取主库用户列表失败");
            e.printStackTrace();
        }
        return resultObject;
    }



    /**
     * 获取从库用户列表
     * @return
     */
    @RequestMapping("findSlaveUserList")
    public Object findSlaveUserList(){
        ResultObject resultObject = new ResultObject();
        try {
            resultObject.setResult(userService.findSlaveUserList());
            resultObject.setCode(200);
            resultObject.setMessage("获取从库用户列表成功");
        } catch (Exception e) {
            resultObject.setCode(-1);
            resultObject.setMessage("获取从库用户列表失败");
            e.printStackTrace();
        }
        return resultObject;
    }
}

七、启动类加扫描mapper注解

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

@SpringBootApplication
@MapperScan(basePackages = "com.gblfy.springboot.mybatisplus.mapper")
public class SpringbootApplication {

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

八、数据库脚本

8.1. masterdb.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	create_time DATETIME DEFAULT NULL COMMENT '创建时间',
	PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone', 18, '[email protected]','2019-01-11 14:20:20'),
(2, 'Jack', 20, '[email protected]','2019-02-05 11:12:22'),
(3, 'Tom', 28, '[email protected]','2019-02-14 08:31:16'),
(4, 'Sandy', 21, '[email protected]','2019-01-14 09:15:15'),
(5, 'Billie', 24, '[email protected]','2019-01-14 09:48:16');

8.2. slavedb.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	create_time DATETIME DEFAULT NULL COMMENT '创建时间',
	PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone2', 18, '[email protected]','2019-01-11 14:20:20'),
(2, 'Jack2', 20, '[email protected]','2019-02-05 11:12:22'),
(3, 'Tom2', 28, '[email protected]','2019-02-14 08:31:16'),
(4, 'Sandy2', 21, '[email protected]','2019-01-14 09:15:15'),
(5, 'Billie2', 24, '[email protected]','2019-01-14 09:48:16');

九、测试验证

9.1. 主库新增用户

http://localhost/user/[email protected]

SpringBoot2.0整合Mybatis-Plus多数据源_第1张图片

9.2. 从库新增用户

http://localhost/user/[email protected]

SpringBoot2.0整合Mybatis-Plus多数据源_第2张图片

9.3. 获取主库用户列表

http://localhost/user/findMasterUserList

SpringBoot2.0整合Mybatis-Plus多数据源_第3张图片

9.4. 获取从库用户列表

http://localhost/user/findSlaveUserList

SpringBoot2.0整合Mybatis-Plus多数据源_第4张图片

9.5.

http://localhost/user/[email protected]

你可能感兴趣的:(SpringBoot2.x)