Springboot+mybatis配置连接两个数据库

 背景:

对于简单地跨库查询我们可以通过跨库SQL和在数据库中提前创建跨库查询视图来实现,但有时我们需要在一个项目中多次使用来自两个数据源的数据,所以就需要在配置中配多个数据源。

实现效果:

一个SpringBoot项目,同时连接两个数据库:比如一个是pgsql数据库,一个是oracle数据库(啥数据库都一样,连接两个同为oracle的数据库,或两个不同的数据库,只需要更改对应的driver-class-name和jdbc-url等即可)

注意:连接什么数据库,要引入对应数据库的包

实现步骤:

1、修改application.yml,添加一个数据库连接配置

(我这里是yml格式,后缀为properties格式是一样的)

server:
  port: 7101
spring:
  jpa:
    show-sql: true
  datasource:
    test1:
      driver-class-name: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://127.0.0.1:5432/test  #测试数据库
      username: root
      password: root

    test2:
      driver-class-name: oracle.jdbc.driver.OracleDriver
      jdbc-url: jdbc:oracle:thin:@127.0.0.1:8888:orcl  #测试数据库
      username: root
      password: root

注意:

(1)使用test1、test2区分两个数据库连接

(2)url改为:jdbc-url

2、使用代码进行数据源注入,和扫描dao层路径(以前是在yml文件里配置mybatis扫描dao的路径)

 新建config包,包含数据库1和数据库2的配置文件

Springboot+mybatis配置连接两个数据库_第1张图片

(1)第一个数据库作为主数据库,项目启动默认连接此数据库

        DataSource1Config.java 

       主数据库都有 @Primary注解,从数据库都没有

package com.test.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 org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.test.dao.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSource1Config {

    @Bean(name = "test1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:test1/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

(2)第二个数据库作为从数据库

        DataSource2Config.java

package com.test.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.test.dao.test2", sqlSessionTemplateRef  = "test2SqlSessionTemplate")
public class DataSource2Config {

    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:test2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

3、 在dao文件夹下,新建test1和test2两个包,分别放两个不同数据库的dao层文件

(1)TestDao1.java

@Component
public interface TestDao1 {

    List selectDailyActivity();

}

(2)TestDao2.java

@Component
public interface TestDao2 {

    List selectDailyActivity();

}

4、 在resource下新建test1和test2两个文件夹,分别放入对应dao层的xml文件

(我原来项目的dao的xml文件在resource目录下,在自己的项目对应目录下即可)

注意dao的java文件和dao的xml文件名字要一致

Springboot+mybatis配置连接两个数据库_第2张图片

(1)TestDao1.xml






    

(2)TestDao2.xml






    

5、测试

在controller文件里,注入两个数据库的dao,分别查询数据

@RestController
public class TestController extends BaseController{

    @Autowired
    private PropertiesUtils propertiesUtils;

    @Autowired
    private TestDao1 testDao1;

    @Autowired
    private TestDao2 testDao2;

    @RequestMapping(value = {"/test/test1"},method = RequestMethod.POST)
    public Result DataStatistics (@RequestBody JSONObject body) throws Exception {
        Result result = new Result<>(ICommon.SUCCESS, propertiesUtils.get(ICommon.SUCCESS));

        JSONObject object = new JSONObject();
        object.put("data",testDao1.selectDailyActivity());
        result.setResult(object);
        return result;
    }

    @RequestMapping(value = {"/test/test2"},method = RequestMethod.POST)
    public Result DataStatisticsaa (@RequestBody JSONObject body) throws Exception {
        Result result = new Result<>(ICommon.SUCCESS, propertiesUtils.get(ICommon.SUCCESS));

        JSONObject object = new JSONObject();
        object.put("data",testDao2.selectDailyActivity());
        result.setResult(object);
        return result;
    }
}

你可能感兴趣的:(数据库,spring,boot,mybatis)