温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot项目中如何同时操作多个数据库

发布时间:2022-03-15 09:08:07 来源:亿速云 阅读:430 作者:iii 栏目:开发技术

本篇内容主要讲解“SpringBoot项目中如何同时操作多个数据库”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot项目中如何同时操作多个数据库”吧!

在实际项目开发中可能存在需要同时操作两个数据库的场景,比如从A库读取数据,进行操作后往B库中写入数据,此时就需要进行多数据库配置。本文以操作本地和线上的MySQL数据库为例:

1、导入相关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配置文件编写

单数据源的配置如下:

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

多数据源的配置如下:

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

经过对比可以发现:
1、多数据源的配置中需要指定具体的名称来区分不同的数据库(上述配置中的dev和local,名称可以根据具体需求自定义)
2、需要使用jdbcUrl代替url

三、数据库连接配置文件

dev数据源配置文件:

@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数据源配置文件:

@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注解的内容来区分不同数据库下的mapper文件,通过@ConfigurationProperties注解来加载指定的数据源

以DevDataSourceConfig为例

SpringBoot项目中如何同时操作多个数据库

四、主启动类注解修改

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

目录结构如下:

SpringBoot项目中如何同时操作多个数据库

五、测试

从dev库中查询数据,取出字段插入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());
        }
    }
}

运行测试代码,从dev库中查出的数据可以成功添加至local库
该方法也适用需要使用多种不同的数据库的场景,比如MySQL和Oracle,修改数据源配置文件即可

到此,相信大家对“SpringBoot项目中如何同时操作多个数据库”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI