Home > Java > javaTutorial > body text

How to configure two data sources in springboot project

不言
Release: 2018-09-20 14:50:11
Original
5370 people have browsed it

The content of this article is about the method of configuring two data sources in the springboot project. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article mainly introduces how to configure two data sources (mysql and oracle) in a springboot project;

1. Introducing related dependencies

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--oracle 驱动 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.1.0.7.0</version>
</dependency>
Copy after login

When the ojdbc driver package version is too low, an error will be reported as shown below, that is, the driver jar is incompatible with the database version:

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

Spring:
        datasource:
            base:
                 driver-class-name: com.mysql.jdbc.Driver
                 jdbc-url: ${base.db.url}
                 username: ${base.db.username}
                 password: ${base.db.password}
            oa:
                 driver-class-name: oracle.jdbc.driver.OracleDriver
                 jdbc-url: ${oa.db.urL}
                 username: ${oa.db.username}
                 password: ${oa.db.password}
            hikari:
                 max-lifetime: 60000
                 login-timeout: 5
                 validation-timeout: 3000
                 connection-timeout: 60000
                 idle-timeout: 60000
Copy after login

3. Multiple data source configuration files, 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 //定义主数据源
    @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 (); }

}
Copy after login

3. Main data source configuration, specify scanning of the corresponding mapper file and the corresponding xml file. When using the mapper file under the mapper package, the corresponding sql session will be automatically used

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();
    }

    /**
     * 配置声明式事务管理器
     */
    @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);
    }
}
Copy after login

4. Second data source configuration, specify 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 automatically used

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();
    }

    /**
     * 配置声明式事务管理器
     */
    @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);
    }
}
Copy after login

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

The above is the detailed content of How to configure two data sources in springboot project. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!