Springboot如何同時裝配兩個相同類型數據庫

同時裝配兩個相同類型數據庫

1.配置文件:

spring:
  profiles:
    active: dev
 
  datasource:
    primary:
      jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB1
      driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
      type: com.alibaba.druid.pool.DruidDataSource
      username: root
      password: root
    secondary:
      jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB2
      driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
      type: com.alibaba.druid.pool.DruidDataSource
      username: root
      password: root

2.配置類:

①主配置類:DataSourceConfigPrimary

@Configuration
@MapperScan(basePackages = "com.message.dao.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class DataSourceConfigPrimary {
 
    // 將這個對象放入Spring容器中
    @Bean(name = "primaryDataSource")
    // 表示這個數據源是默認數據源
    @Primary
    // 讀取application.properties中的配置參數映射成為一個對象
    // prefix表示參數的前綴
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource getDateSourcePrimary()
    {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "primarySqlSessionFactory")
    // 表示這個數據源是默認數據源
    @Primary
    // @Qualifier表示查找Spring容器中名字為test1DataSource的對象
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));
        return bean.getObject();
    }
 
    @Bean("primarySqlSessionTemplate")
    // 表示這個數據源是默認數據源
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(
            @Qualifier("primarySqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

②次配置類:DataSourceConfigSecondary

@Configuration
@MapperScan(basePackages = "com.message.dao.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class DataSourceConfigSecondary {
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource getDateSource2()
    {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/secondary/*.xml"));
        return bean.getObject();
    }
 
    @Bean("secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(
            @Qualifier("secondarySqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

3.掃描XML

4.啟動類:

@SpringBootApplication(scanBasePackages = {"com.lalal.*"})
public class MessageApplication extends SpringBootServletInitializer { 
    public static void main(String[] args) {
        SpringApplication.run(MessageApplication.class, args);
    }
 
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

配置連接兩個或多個數據庫

背景:

項目中需要從兩個不同的數據庫查詢數據,之前實現方法是:springboot配置連接一個數據源,另一個使用jdbc代碼連接。

為瞭改進,現在使用SpringBoot配置連接兩個數據源

實現效果:

一個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的配置文件

(1)第一個數據庫作為主數據庫,項目啟動默認連接此數據庫

DataSource1Config.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.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);
    }
}

特別註意:

(1)主數據庫都有 @Primary註解,從數據庫都沒有

(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<DailyActivityDataMiddle> selectDailyActivity(); 
}

(2)TestDao2.java

@Component
public interface TestDao2 { 
    List<MovieShowTest> selectDailyActivity(); 
}

4、 在resource下新建test1和test2兩個文件夾,分別放入對應dao層的xml文件

(我原來項目的dao的xml文件在resource目錄下,你們在自己的項目對應目錄下即可)

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

(1)TestDao1.xml

<?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.test.dao.test1.TestDao1"> 
    <select id="selectDailyActivity" resultType="com.test.pojo.DailyActivityDataMiddle"> 
        SELECT * FROM daily_activity_data_middle 
    </select> 
</mapper>

(2)TestDao2.xml

<?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.test.dao.test2.TestDao2"> 
    <select id="selectDailyActivity" resultType="com.test.pojo.MovieShowTest"> 
        SELECT * FROM movieshowtest 
    </select> 
</mapper>

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<JSONObject> DataStatistics (@RequestBody JSONObject body) throws Exception {
        Result<JSONObject> 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<JSONObject> DataStatisticsaa (@RequestBody JSONObject body) throws Exception {
        Result<JSONObject> result = new Result<>(ICommon.SUCCESS, propertiesUtils.get(ICommon.SUCCESS)); 
        JSONObject object = new JSONObject();
        object.put("data",testDao2.selectDailyActivity());
        result.setResult(object);
        return result;
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: