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包下进行不同数据库的交互即可。