示例代码地址:
https://github.com/sushizhendeqiang/mybatis-datasource-demo

一、迅速创建项目(基于idea)

1.png

pom.xml文件预览:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

这里我又增加了druid以及lombok的依赖。

二、数据源连接配置

在application.yml文件中添加我们的数据库连接配置,这里我添加了one、two两个数据库配置:

spring:
  datasource:
    one:
      url: jdbc:mysql://127.0.0.1:3306/test01?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&tinyInt1isBit=false
      username: root
      password: admin
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource

    two:
      url: jdbc:mysql://127.0.0.1:3306/test02?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&tinyInt1isBit=false
      username: root
      password: admin
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource

添加数据源配置类,获取我们在yml文件中添加的数据库配置:
(@Bean 告诉方法,产生了一个bean对象;@ConfigurationProperties 获取参数配置;注解在这里不做详细介绍,有疑问的同学可以查一下~)

package mybatis.datasource.demo.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @Author: sush4
 * @Description:多数据源配置
 * @Date: 2020/7/15
 */
@Configuration
@PropertySource(value = "classpath:application.yml")
public class DataSourceConfig {

    /**
     * @return
     * @Description: * @Bean 告诉方法,产生了一个bean对象
     * * @ConfigurationProperties 获取参数配置
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dataSourceOne() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dataSourceTwo() {
        return DruidDataSourceBuilder.create().build();
    }
}

三、mybatis配置

这里要自己手动配置mybatis:
(通过@Configuration注解配置的,不能读取到mapper的xml文件的位置,需要自行配置mapper路径)

package mybatis.datasource.demo.config.mybatis;

import org.apache.ibatis.annotations.Param;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Author: sush4
 * @Description:数据源1配置
 * @Date: 2020/7/15
 */
@Configuration
@MapperScan(basePackages = "mybatis.datasource.demo.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisConfig1 {
    @Resource(name = "dataSourceOne")
    DataSource dataSourceOne;

    @Bean
    SqlSessionFactory sqlSessionFactory1() {
        SqlSessionFactory sessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSourceOne);
            //通过@Configuration注解配置的,不能读取到mapper的xml文件的位置
            //需要自行配置mapper路径
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
            sessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }
    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {
        return new SqlSessionTemplate(sqlSessionFactory1());
    }
}

datasource2同理,此处不再赘述;
***mapper.xml、controller等不在此做介绍,只是一个简单的示例。

四、示例目录结构

2.png
代码示例已上传github,有兴趣的同学可以看一下~

五、运行结果

demo_test01中数据 1,name1
demo_test02中数据 1,name2
3.jpg
over!掰掰~~~



有理解不正确的地方,望指正!谢谢阅读。



参考资料:
1.https://blog.csdn.net/u012702547/article/details/88761979

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

一个喜欢拔刀的萌新Coder