springboot -- multiple data sources

This paper mainly introduces how to configure two data sources (mysql and oracle) in a spring boot project;

1. Import related dependence

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--oracle drive -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.1.0.7.0</version>
</dependency>

When the version of the ojdbc driver package is too low, an error will be reported as shown in the following figure, that is, the driver jar is not compatible with the database version:

2. Configure the data source connection parameters in applicationContext.yml:

 1     Spring:
 2         datasource:
 3             base:
 4                  driver-class-name: com.mysql.jdbc.Driver
 5                  jdbc-url: ${base.db.url}
 6                  username: ${base.db.username}
 7                  password: ${base.db.password}
 8             oa:
 9                  driver-class-name: oracle.jdbc.driver.OracleDriver
10                  jdbc-url: ${oa.db.urL}
11                  username: ${oa.db.username}
12                  password: ${oa.db.password}
13             hikari:
14                  max-lifetime: 60000
15                  login-timeout: 5
16                  validation-timeout: 3000
17                  connection-timeout: 60000
18                  idle-timeout: 60000

3. Multi data source configuration file, read the corresponding connection parameters

Package com.**.config;

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 javax.sql.DataSource;

public class MultiDataSourceConfig {

    @Bean (name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary //Define master data source
    @ConfigurationProperties (prefix = "spring.datasource.Base")
    public DataSource primaryDataSource () { return DataSourceBuilder.create().build (); }

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

}

3. The configuration of the main data source specifies to scan the corresponding mapper file and the corresponding xml file. When using the mapper file under the mapper package, the corresponding sql session will be used automatically

Package com.**.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframeworkcore.io.support.PathMatchingResourcePatternResolver;
import org.spr ingframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = "com.**.mapper", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class SqlSessionTemplate1 {

    @Bean (name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory  (@Qualifier("primaryDataSource") DataSource dataSource)
            throws Exception{
        SqLSessionFactoryBean bean = new SqlSessionFactoryBean ();
        bean.setDataSource (dataSource);
        bean.setMapperLocations (new PathMatchingResourcePatternResolver().getResources (locationPattern: "classpath: mybatis/mapper/*. XmL"));
        return bean.getObject();
    }

    /**
     * Configure declarative transaction manager
     */
    @Bean (name = "primaryTransactionManager")
    @Primary
    public PlatformTransactionManager primaryTransactionManager  (@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager  (dataSource);
    }

    @Bean (name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplatel primarySqlSessionTemplate(@Qualifier("primarySqlSesionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplatel(sqlSessionFactory);
    }
}

4. The second data source configuration specifies to scan the corresponding mapper file and the corresponding xml file. When using the mapper file under the mapper package, the corresponding sql session will be used automatically

Package com.**.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.secondary;
import org.springframeworkcore.io.support.PathMatchingResourcePatternResolver;
import org.spr ingframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = "com.**.oraclemapper", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SqlSessionTemplate2 {

    @Bean (name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory  (@Qualifier("secondaryDataSource") DataSource dataSource)
            throws Exception{
        SqLSessionFactoryBean bean = new SqlSessionFactoryBean ();
        bean.setDataSource (dataSource);
        bean.setMapperLocations (new PathMatchingResourcePatternResolver().getResources (locationPattern: "classpath: mybatis/oraclemapper/*. XmL"));
        return bean.getObject();
    }

    /**
     * Configure declarative transaction manager
     */
    @Bean (name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager  (@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager  (dataSource);
    }

    @Bean (name = "secondarySqlSessionTemplate")
    public SqlSessionTemplatel secondarySqlSessionTemplate(@Qualifier("secondarySqlSesionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplatel(sqlSessionFactory);
    }
}

At this point, the service layer can be used as a single data source.

Keywords: Java Spring Mybatis JDBC MySQL

Added by DjNaF on Sun, 29 Dec 2019 19:42:04 +0200