溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫

發(fā)布時(shí)間:2022-03-15 09:08:07 來源:億速云 閱讀:439 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫”吧!

在實(shí)際項(xiàng)目開發(fā)中可能存在需要同時(shí)操作兩個(gè)數(shù)據(jù)庫的場景,比如從A庫讀取數(shù)據(jù),進(jìn)行操作后往B庫中寫入數(shù)據(jù),此時(shí)就需要進(jìn)行多數(shù)據(jù)庫配置。本文以操作本地和線上的MySQL數(shù)據(jù)庫為例:

1、導(dǎo)入相關(guān)pom文件

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.3</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

二、application.yml配置文件編寫

單數(shù)據(jù)源的配置如下:

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

多數(shù)據(jù)源的配置如下:

spring:
  datasource:
    dev:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://xxx.xx.xx.xx:3306/meal_order?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource
    local:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://127.0.0.1:3306/db2021?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource

經(jīng)過對比可以發(fā)現(xiàn):
1、多數(shù)據(jù)源的配置中需要指定具體的名稱來區(qū)分不同的數(shù)據(jù)庫(上述配置中的dev和local,名稱可以根據(jù)具體需求自定義)
2、需要使用jdbcUrl代替url

三、數(shù)據(jù)庫連接配置文件

dev數(shù)據(jù)源配置文件:

@Configuration
@MapperScan(basePackages = "com.multiple.mapper.dev",sqlSessionFactoryRef = "devSqlSessionFactory")
public class DevDataSourceConfig {
    @Primary
    @Bean(name = "devDataSource")
    @ConfigurationProperties("spring.datasource.dev")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "devSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("devDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapping/dev/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

local數(shù)據(jù)源配置文件:

@Configuration
@MapperScan(basePackages = "com.multiple.mapper.local",sqlSessionFactoryRef = "localSqlSessionFactory")
public class LocalDataSourceConfig {
    @Primary
    @Bean(name = "localDataSource")
    @ConfigurationProperties("spring.datasource.local")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "localSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("localDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapping/local/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

不同配置文件通過@MapperScan注解的內(nèi)容來區(qū)分不同數(shù)據(jù)庫下的mapper文件,通過@ConfigurationProperties注解來加載指定的數(shù)據(jù)源

以DevDataSourceConfig為例

SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫

四、主啟動類注解修改

@SpringBootApplication(exclude={<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->DataSourceAutoConfiguration.class})

目錄結(jié)構(gòu)如下:

SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫

五、測試

從dev庫中查詢數(shù)據(jù),取出字段插入local庫中:

public interface DevMapper {
    @Select("select * from test")
    List<Test> getAllTest();
}
public interface LocalMapper {
    @Insert("insert into payment(serial) values (#{name})")
    int insertMessage(String name);
}
@SpringBootTest
class MultipleDatabaseApplicationTests {

    @Autowired
    private DevMapper devMapper;

    @Autowired
    private LocalMapper localMapper;

    @Test
    void contextLoads() {
        List<com.multiple.pojo.Test> testList = devMapper.getAllTest();
        for(com.multiple.pojo.Test test : testList){
            localMapper.insertMessage(test.getAa());
        }
    }
}

運(yùn)行測試代碼,從dev庫中查出的數(shù)據(jù)可以成功添加至local庫
該方法也適用需要使用多種不同的數(shù)據(jù)庫的場景,比如MySQL和Oracle,修改數(shù)據(jù)源配置文件即可

到此,相信大家對“SpringBoot項(xiàng)目中如何同時(shí)操作多個(gè)數(shù)據(jù)庫”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI