1、添加依赖

mysql依赖

<!--  mysql依赖 [start]  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--  mysql依赖 [end]  -->

mybatis依赖

<!--  集成mybatis框架 [start]  -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--  集成mybatis框架 [end]  -->

json依赖

<dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
2、配置application.properties

注意:url必须使用jdbc-url

#端口号
server.port=8080
# 数据库blog
spring.datasource.blog.jdbc-url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.blog.username=root
spring.datasource.blog.password=root
spring.datasource.blog.driver-class-name=com.mysql.cj.jdbc.Driver

# 数据库monitor
spring.datasource.monitor.jdbc-url=jdbc:mysql://localhost:3306/monitor?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.monitor.username=root
spring.datasource.monitor.password=root
spring.datasource.monitor.driver-class-name=com.mysql.cj.jdbc.Driver
####################Mybatis配置####################
# 实体类包路径
mybatis.type-aliases-package=com.gh.blog.entity
# mybatis的映射器XML文件路径
mybatis.mapper-locations=classpath*:mapper/*.xml
3、创建各层的包和类

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring

  • entity包
    Demo实体类对应的是blog数据库的表,Loginmonitor实体类对应的是monitor实体类的表;
    实体类都实现序列化、以及重写toString方法(方便该类型的List数据转JSON)
  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring boot_02


  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring_03

  • dao包
    各个数据源的DAO包要分开
  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring boot_04

@Repository
public interface DemoDao {
    List<Demo> getAll();
}

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_mysql_05

@Repository
public interface LoginmonitorDao {
    List<Loginmonitor> getAll();

    void addList(List<Loginmonitor> list);
}
  • mapper包
    各个数据源的mapper同样也要分开

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_mysql_06

<?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.gh.blog.dao.blog.DemoDao">

<!-- 查询信息 -->
<select id="getAll" resultType="com.gh.blog.entity.Demo">
      select * from demo
    </select>
</mapper>

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring boot_07

<?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.gh.blog.dao.monitor.LoginmonitorDao">

    <!-- 查询信息 -->
    <select id="getAll" resultType="com.gh.blog.entity.Loginmonitor">
      select * from loginmonitor
    </select>

    <insert id="addList">
        insert into loginmonitor(id, ip)
        values
        <foreach collection="list" item="bo" separator=",">
            (#{bo.id}, #{bo.ip})
        </foreach>
    </insert>
</mapper>
  • service包
    service层的接口和dao层的一样,只是不需要添加注解
  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring boot_08


  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_数据库_09

  • impl包
    实现service层的接口类,要添加@Service注解
  • springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_mybatis_10

@Service
public class DemoImpl implements DemoService {
    @Autowired
    private DemoDao dao;

    @Override
    public List<Demo> getAll() {
        return dao.getAll();
    }
}

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring boot_11

@Service
public class LoginmonitorImpl implements LoginmonitorService {
    @Autowired
    private LoginmonitorDao dao;

    @Override
    public List<Loginmonitor> getAll() {
        return dao.getAll();
    }

    @Override
    public void addList(List<Loginmonitor> list) {
        dao.addList(list);
    }
}
  • controller包
    这里使用了RESTful规范,前台请求方式可以参考另一篇文章
    前台使用Ajax请求后台RESTful规范的API接口 也可以使用Postman工具进行测试
/**
 * @author gaohan
 * @version 1.0
 * @date 2020/8/11 21:10
 */
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)	
public class TestController {

    @Autowired
    private DemoService demoService;

    @Autowired
    private LoginmonitorService loginmonitorService;

    @GetMapping(value = "/demo")
    public String demo(){
        List<Demo> list = demoService.getAll();
        System.err.println(list.toString());
        return list.toString();
    }

    @GetMapping(value = "/login")
    public String login(){
        List<Loginmonitor> list = loginmonitorService.getAll();
        System.err.println(list.toString());
        return list.toString();
    }

    @PostMapping(value = "/add")
    public String add(@RequestBody List<Loginmonitor> list) {
        System.err.println(list.toString());
        loginmonitorService.addList(list);
        return "SUCCESS!";
    }
}
4、创建数据源

最重要的一步
blog数据库的数据源,使用@Primary注解标识为默认数据源

package com.gh.blog.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author gaohan
 * @version 1.0
 * @date 2020/8/12 16:43
 */
//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.gh.blog.dao.blog", sqlSessionFactoryRef = "blogSqlSessionFactory")
public class DataSourceConfig_Blog {

    // 将这个对象放入Spring容器中
    @Bean(name = "blogDataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀,要和application.properties配置里的参数对上
    @ConfigurationProperties(prefix = "spring.datasource.blog")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "blogSqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为blogDataSource的对象
    public SqlSessionFactory blogSqlSessionFactory(@Qualifier("blogDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/blog/*.xml"));
        return bean.getObject();
    }

    @Bean("blogSqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate blogSqlSessionTemplate(
            @Qualifier("blogSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

monitor数据库的数据源

package com.gh.blog.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author gaohan
 * @version 1.0
 * @date 2020/8/12 16:43
 */
//表示这个类为一个配置类
@Configuration
@MapperScan(basePackages = "com.gh.blog.dao.monitor", sqlSessionFactoryRef = "monitorSqlSessionFactory")
public class DataSourceConfig_Monitor {

    @Bean(name = "monitorDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.monitor")
    public DataSource getDateSource2() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "monitorSqlSessionFactory")
    public SqlSessionFactory monitorSqlSessionFactory(@Qualifier("monitorDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/monitor/*.xml"));
        return bean.getObject();
    }

    @Bean("monitorSqlSessionTemplate")
    public SqlSessionTemplate monitorSqlSessionTemplate(
            @Qualifier("monitorSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}
5、测试

blog数据库demo表数据查询

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_数据库_12


monitor数据库loginmonitor表数据插入

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_spring_13


monitor数据库loginmonitor表数据查询

springboot 配置mysql sqlserver多数据源 springboot mybatis配置多数据源_mybatis_14