SpringBoot: multi data source configuration based on MyBatis


preface

Previously, in the process of using SpringBoot to build background services, we usually access a database and a data source The MQTT service used in the new project needs authentication, but the MQTT service is used by multiple projects, so its authentication database is in a separate database. At this time, we need to configure multiple data sources in SpringBoot

On the whole, it's relatively simple, but I've been tossing around for more than a day. Now I don't understand many principles. This can only be regarded as a record for future search


Configure application yml

First, in application Two data sources are configured in YML. Here, I will take my project as an example. The data source of the main database is called main and the mqtt database is called mqtt. You can customize it here, but please describe it more The details are as follows

spring:
  datasource:
    main:
      url: jdbc:mysql://************************************
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
    mqtt:
      url: jdbc:mysql://************************************
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver

Multi data source configuration class

Add a DataSourceConfig data source configuration class The specific code is as follows

/**
 * Database multi data source configuration
 */
@Configuration
public class DataSourceConfig {

    // GreenRoom master database configuration
    @Primary
    @Bean(name = "mainDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.main")
    public DataSourceProperties mainDataSourceProperties() {
        return new DataSourceProperties();
    }

    // GreenRoom master database data source
    @Primary
    @Bean(name = "mainDataSource")
    public DataSource mainDataSource(@Qualifier("mainDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    // mqtt database data source configuration
    @Bean(name = "mqttDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.mqtt")
    public DataSourceProperties mqttDataSourceProperties() {
        return new DataSourceProperties();
    }

    // mqtt database data source
    @Bean("mqttDataSource")
    public DataSource mqttDataSource(@Qualifier("mqttDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
}

Main and Mqtt data source configuration classes

The multi data source configuration class has been set above. Next, we will configure the Main and Mqtt data sources separately. The significance of separate configuration is to let Main and Mqtt scan their Dao Java and Dao xml.

First of all, let's take a look at the specific directory structure of my project. It may not be standardized... Forgive me

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wmbun8sr-1628566763554)( https://i.loli.net/2021/08/10/SGo7u3lQDkajRPN.png )]

Next, let's take a specific look at the configuration class of main data source. Here, take the GreenRoomDataSourceConfig in my project as an example

/**
 * Master database Mapper configuration
 */
@Configuration
@MapperScan(basePackages ="com.dong.gen.mapper", sqlSessionTemplateRef  = "mainSqlSessionTemplate")
public class GreenRoomDataSourceConfig {

    // Master data source main data source
    @Primary
    @Bean("mainSqlSessionFactory")
    public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:com/dong/gen/mapper/**/*.xml"));
        return sqlSessionFactory.getObject();
    }

    @Primary
    @Bean(name = "mainTransactionManager")
    public DataSourceTransactionManager mainTransactionManager(@Qualifier("mainDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "mainSqlSessionTemplate")
    public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

Then take a look at the MqttDataSourceConfig configuration class

/**
 * MQTT Database Mapper configuration
 */
@Configuration
@MapperScan(basePackages ="com.dong.mqtt.mapper", sqlSessionTemplateRef  = "mqttSqlSessionTemplate")
public class MqttDataSourceConfig {
    // MQTT data source
    @Bean("mqttSqlSessionFactory")
    public SqlSessionFactory mqttSqlSessionFactory(@Qualifier("mqttDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:com/dong/mqtt/mapper/*.xml"));
        return sqlSessionFactory.getObject();
    }

    @Bean(name = "mqttTransactionManager")
    public DataSourceTransactionManager mqttTransactionManager(@Qualifier("mqttDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mqttSqlSessionTemplate")
    public SqlSessionTemplate mqttSqlSessionTemplate(@Qualifier("mqttSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
} 

The core of these two files is the package scanning configuration code, as shown below

@MapperScan(basePackages ="com.dong.gen.mapper", sqlSessionTemplateRef  = "mainSqlSessionTemplate")

sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:com/dong/gen/mapper/**/*.xml"));
@MapperScan(basePackages ="com.dong.mqtt.mapper", sqlSessionTemplateRef  = "mqttSqlSessionTemplate")

sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:com/dong/mqtt/mapper/*.xml"));

epilogue

At this point, the SpringBoot + MyBatis multi data source configuration is completed. If you have any questions, please comment. Thank you


Keywords: Java Maven Mybatis Spring Spring Boot

Added by Dillenger on Mon, 27 Dec 2021 12:20:53 +0200