MyBatis - SpringBoot配置多数据源

一、场景

有时候项目中需要连接多个数据库,记录下SpringBoot如何中配置多数据源。

二、配置

2.1 pom

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- druid -->
<dependency>
   	<groupId>com.alibaba</groupId>
   	<artifactId>druid-spring-boot-starter</artifactId>
   	<version>1.1.2</version>
</dependency>

2.2 禁用数据源自动配置

SpringBoot的DataSourceAutoConfiguration会读取application.yml文件的spring.datasource.*属性并自动配置单数据源。

@SpringBootApplication注解中通过exclude属性将该类给排除掉。

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

注:

  • 不排除掉DataSourceAutoConfiguration,在配置多数据源会报错,大概意思就是创建DataSourceInitializer时,init()方法中找到了多个数据源(根据DataSource类型查找),报错信息如下:

Error creating bean with name ‘dataSourceInitializer’: Invocation of init method failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘javax.sql.DataSource’ available: expected single matching bean but found 2: db1DataSource,db2DataSource

解决方法:

  1. 排除掉DataSourceAutoConfiguration
  2. 指定主数据源:DataSourceInitializer是用来执行数据库初始化脚本,假如不需要初始化的话,临时解决方法就是任意指定个主数据源

2.2 application.yml

spring:
  datasource:
    db1:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
      username: root
      password: root
    db2:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
      username: root
      password: root

2.3 数据源配置

2.3.1 db1配置

  1. @MapperScan注解需要放在具体的数据源配置上,basePackages指定扫描的Mapper接口,sqlSessionFactoryRef指定使用的sqlSessionFactory
@Configuration
@MapperScan(basePackages = "com.momo.mytt.biz.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class Db1DataSourceConfig {

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

    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // 设置db1数据源
        bean.setDataSource(dataSource);
        // 设置db1的xxxMapper.xml文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/momo/mytt/mapper/db1/*.xml"));
        return bean.getObject();
    }

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

	// 事务配置略
}

2.3.2 db2配置

  1. 和db1配置类似
@Configuration
@MapperScan(basePackages = "com.momo.mytt.biz.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class Db2DataSourceConfig {

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

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 设置db2的xxxMapper.xml文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/momo/mytt/mapper/db2/*.xml"));
        return bean.getObject();
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
	
	// 事务配置略
}

2.4 Mapper.xml配置

根据数据源中配置的Mpper.xml路径,放置对应的文件

2.5 Mapper接口

根据@Mapper注解的basePackages属性配置的包名,放置对应的Mapper接口

三、测试

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值