基于springboot和mybatis的多数据源配置

基于springboot和mybatis的多数据源配置

1、首先新建一个springboot项目,项目结构如下:
基于springboot和mybatis的多数据源配置_第1张图片
引入mybatis和mysql依赖:

>
        >org.mybatis.spring.boot>
        >mybatis-spring-boot-starter>
       >2.1.3>
 >
 >
     >mysql>
     >mysql-connector-java>
     >runtime>
 >

2、建立两个数据源的测试数据库及表,这里为了更好的验证,选择本地数据库为第一个数据源,服务器远端数据库作为第二个数据源
基于springboot和mybatis的多数据源配置_第2张图片
数据源1的数据在上图可查看到,数据源2的表数据如下:
基于springboot和mybatis的多数据源配置_第3张图片
3、使用自动生成工具分别生成两个数据源的mapper接口、xml文件、pojo,并放进不同的地方如下:
基于springboot和mybatis的多数据源配置_第4张图片

4、在yml配置文件中添加数据源信息
首先新建一个配置文件application-local.yml,添加数据库信息(之所以独立出来,考虑主配置文件会掺杂很多其他配置)

datasource:
  data1: #数据源1
    host: localhost
    username: root
    password: 123456
  data2: #数据源2
    host: ***
    username: ***
    password: ***

主配置文件application.yml里信息如下:

spring:
  profiles:
    active: local #引入application-local.yml
  #多数据源配置
  datasource1:
    url: jdbc:mysql://${datasource.data1.host}/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: ${datasource.data1.username}
    password: ${datasource.data1.password}
  datasource2:
    url: jdbc:mysql://${datasource.data2.host}/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: ${datasource.data2.username}
    password: ${datasource.data2.password}

5、编写数据源配置类

package com.example.mydemo.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author: ChenGang
 * @create: 2020-06-23 19:23
 * @description 数据源配置类
 **/
@Configuration
public class DataSourceConfig {
    /*********************************** 数据源1属性读取 **********************************/
    //数据源1配置文件读取
    @Primary
    @Bean(name = "dataSourceProperties1")
    @ConfigurationProperties(prefix = "spring.datasource1")
    public DataSourceProperties dataSourceProperties1(){
        return new DataSourceProperties();
    }

    //配置数据源1
    @Primary
    @Bean(name = "dataSource1")
    public DataSource dataSource1(@Qualifier("dataSourceProperties1") DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    /*********************************** 数据源2属性读取 **********************************/
    //数据源2配置文件读取
    @Bean(name = "dataSourceProperties2")
    @ConfigurationProperties(prefix = "spring.datasource2")
    public DataSourceProperties dataSourceProperties2(){
        return new DataSourceProperties();
    }

    //配置数据源2
    @Bean(name = "dataSource2")
    public DataSource dataSource2(@Qualifier("dataSourceProperties2") DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
}

6、编写mybatis配置类
*数据源1的mybatis配置====>*

package com.example.mydemo.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.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: ChenGang
 * @create: 2020-06-23 19:37
 * @description 数据源1的mybatis配置类
 **/
@Configuration
@MapperScan(basePackages = "com.example.mydemo.mapper.data1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisConfig1 {

    //配置sqlSession工厂
    @Primary
    @Bean(name = "sqlSessionFactory1")
    public SqlSessionFactory mainSqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        //设置数据源
        sqlSessionFactory.setDataSource(dataSource);
        //设置mapper映射文件
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath:mapper/data1/*.xml"));

        return sqlSessionFactory.getObject();
    }

    //配置sqlSession模板引擎
    @Primary
    @Bean(name = "sqlSessionTemplate1")
    public SqlSessionTemplate sqlSessionTemplate1(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

*数据源2的mybatis配置====>*

package com.example.mydemo.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.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: ChenGang
 * @create: 2020-06-23 19:37
 * @description 数据源1的mybatis配置类
 **/
@Configuration
@MapperScan(basePackages = "com.example.mydemo.mapper.data2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MybatisConfig2 {

    //配置sqlSession工厂
    @Primary
    @Bean(name = "sqlSessionFactory2")
    public SqlSessionFactory mainSqlSessionFactory2(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        //设置数据源
        sqlSessionFactory.setDataSource(dataSource);
        //设置mapper映射文件
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath:mapper/data2/*.xml"));

        return sqlSessionFactory.getObject();
    }

    //配置sqlSession模板引擎
    @Primary
    @Bean(name = "sqlSessionTemplate2")
    public SqlSessionTemplate sqlSessionTemplate2(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

7、数据库连接池配置类

package com.example.mydemo.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @author: ChenGang
 * @create: 2020/6/23:20:58
 * @description: 数据库连接池配置
 **/
@Configuration
public class JdbcTemplateDataSourceConfig {

    //JdbcTemplate主数据源ds1数据源
    @Bean(name = "jdbcTemplate1")
    public JdbcTemplate jdbcTemplate1(@Qualifier("dataSource1") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    //JdbcTemplate第二个ds2数据源
    @Bean(name = "jdbcTemplate2")
    public JdbcTemplate jdbcTemplate2(@Qualifier("dataSource2") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

8、编写测试类,分别查询两张表数据

package com.example.mydemo;

import com.example.mydemo.mapper.data1.Test1Mapper;
import com.example.mydemo.mapper.data2.Test2Mapper;
import com.example.mydemo.pojo.data1.Test1;
import com.example.mydemo.pojo.data2.Test2;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class MydemoApplicationTests {

    @Resource
    Test1Mapper test1Mapper;
    @Resource
    Test2Mapper test2Mapper;
    @Test
    void contextLoads() {
        Test1 test1 = test1Mapper.selectByPrimaryKey(1);
        System.out.println("数据源1的数据:"+test1);
        List<Test2> test2s = test2Mapper.findAll();
        System.out.println("数据源2的数据:"+test2s.get(0));
    }

}

打印结果如下:
在这里插入图片描述
可以看见,当使用test1Mapper做查询时链接数据源1,获取的数据源1的数据;当使用test2Mapper做查询时链接数据源2,获取的数据源2的数据,多数据源的配置就成功啦!

如有不对,请留言指正!下期请见多数据源的事务配置。

你可能感兴趣的:(Java基础,mybatis,spring,boot)