springboot项目连接多种数据库如何操作?

在项目的开发中,经常会遇到需要连接多个多种数据库的情况,mysql、oracle等等,下面详细讲解如何在一个服务中进行多种数据库的配置。

第一步:

在yml配置文件中配置多个数据源,如下,根据实际情况更改自己的配置即可。

spring:
  datasource:
    # 配置多个数据源
    primary:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:oracle:thin:@171.28.7.55:1521:example
      username: root
      password: root
      driver-class-name: oracle.jdbc.OracleDriver  #数据库链接驱动
    secondary:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:mysql://127.0.0.1:3306/exinfo?useUnicode=true&characterEncoding=utf-8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver  #数据库链接驱动

第二步:

创建多个配置类,以配置oracle和mysql两个数据库为例,可参考代码进行延展。

1.在配置类中需要进行数据源配置

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }
@ConfigurationProperties(prefix = "spring.datasource.primary")用于绑定yml中的第一个数据源配置,这些配置项会被自动映射到db1DataSource所创建的数据源实例中。通过DataSourceBuilder. create()创建一个新的数据源构建器,并调用.build()方法来完成数据源实例的创建。

如果有多个相同类型的Bean,使用@Primary注解可以标记出一个优先(默认)使用的Bean。所以使用最多的数据库可以使用@Primary注解。

2.配置MyBatis的SqlSessionFactory,它是MyBatis操作数据库的核心组件,负责创建SqlSession对象,执行SQL语句等。使用名称为db1DataSource的数据源Bean作为构造SqlSessionFactory的依赖。

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        return bean.getObject();
    }

3.配置事务管理器(DataSourceTransactionManager),它基于数据源(DataSource)的事务管理实现,专门用于JDBC事务处理。注解明确指定使用名为db1DataSource的数据源Bean。

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

4.配置SqlSessionTemplate实例,它是MyBatis与Spring集成的关键组件,提供了线程安全的SQL会话执行环境。

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

5.类注解@MapperScan

  • basePackages= "com.example.mapper":指定了Mapper接口所在的包路径。Spring会扫描这个包及其子包下的所有接口,如果接口符合MyBatis Mapper的规范,Spring会自动生成代理对象来处理SQL调用。
  • sqlSessionTemplateRef = "db1SqlSessionTemplate":指定了与Mapper接口绑定的sqlSessionTemplate的名称。在执行Mapper接口的方法时,Spring会使用这个指定的sqlSessionTemplate来管理SQL会话。这里的db1SqlSessionTemplate是之前通过@Bean方法定义的sqlSessionTemplate Beam的名称。

DataSourcePrimaryConfig完整代码如下:

package com.example.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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSourcePrimaryConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        return bean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

DataSourceSecondaryConfig代码如下:

package com.example.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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DataSourceSecondaryConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

第三步:

根据配置文件,创建两个mapper包如下:

在不同的mapper包下进行不同数据库的交互即可。

  • 82
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不柔情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值