Spring Boot integrate multiple data sources MyBatis

Spring Boot integrate multiple data sources MyBatis

In the development of complex applications, the application may involve a plurality of data sources connected to a so-called multi-source data is defined herein as the connecting at least two or more of the database.

First, create a Spring Boot Project

Add MyBatis, Druid dependent (Druid here must be designed for the Spring boot build Druid, you can not use the traditional Druid), MySQL and Web dependent, complete dependence as follows:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--注意配置版本号-->
            <version>5.1.28</version>
     https://i.cnblogs.com/EditCategories.aspx?catid=1       <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

Multiple Data Source Configuration

Next configure multiple data sources, the basic information in the configuration database application.properties then provided to two DataSource, simple application.properties following configuration:

spring.datasource.one.url=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.one.username=root
spring.datasource.one.password=123456
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.two.url=jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
spring.datasource.two.username=root
spring.datasource.two.password=123456
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

Then create DataSourceConfig configuration class, the configuration inside the corresponding two data sources:

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DruidDataSource dsOne() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DruidDataSource dsTwo() {
        return DruidDataSourceBuilder.create().build();
    }
}

MyBatis configuration

Here we need to configure two Bean, so two data sources arranged in two categories:

@Configuration//声明该类是一个配置类
@MapperScan(basePackages = "com.lwh.mybatistest.mapper", sqlSessionFactoryRef = "sqlSessionFactory1", sqlSessionTemplateRef = "sqlSessionTemplate1")
//扫描的包是com.lwh.mybatistest.mapper
//SqlSessionFactory根据dsOne创建,然后再根据创建好的SqlSessionFactory创建一个SqlSessionTemplate。
public class MyBatisConfigOne {
    @Resource(name = "dsOne")
    DataSource dsOne;

    @Bean
    SqlSessionFactory sqlSessionFactory1() {
        SqlSessionFactory sessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dsOne);
            sessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {
        return new SqlSessionTemplate(sqlSessionFactory1());
    }
}

According to a first configuration, a second configuration data sources to note here because the operations are different data sources, the scanning of the package is not the same, different operation Mapper different data sources. as follows:

@Configuration//声明该类是一个配置类
@MapperScan(basePackages = "com.lwh.mybatistest.mapper2", sqlSessionFactoryRef = "sqlSessionFactory2", sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {
    @Resource(name = "dsTwo")
    DataSource dsTwo;

    @Bean
    SqlSessionFactory sqlSessionFactory2() {
        SqlSessionFactory sessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dsTwo);
            sessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate2() {
        return new SqlSessionTemplate(sqlSessionFactory2());
    }
}

Project is structured as follows:

The above mapper.xml file is generated using MyBatis reverse engineering, not repeat them here.
In Maven project, the official suggested that we put XML files in the resources file, if placed under java, packaged items will be automatically filtered out, so we Maven configuration file, so that projects do not filter our XML file so we need pom.xml configuration file bulid node which added configuration information, as follows:

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
</build>

Such projects when packaged and released, it will not filter out our mapper.xml files

One database of data:

The data for the two databases:

Now type of test to test our configuration was successful:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatistestApplicationTests {

    @Autowired
    BookMapper bookMapper;
    @Autowired
    BookMapper2 bookMapper2;
    @Test
    public void contextLoads() {
        List<Book> list = bookMapper.getAllBook();
        System.out.println("第一个:" + list);
        System.out.println("第二个:" + bookMapper2.getAllBook());

    }

}

The output is:

First: [Book {id = 1, bookname = ' Three Kingdoms', author = 'Luo Guanzhong'}]
Second: [Book {id = 2, bookname = ' Dream of the Red', author = 'Cao Xueqin'}]

Therefore, the operation of multiple data sources to configure our project a success!

to sum up:

1, first to Spring Boot project-related dependencies introduced.
2, the configuration information in multiple databases application.properties, create a DataSource configuration class.
3, are arranged corresponding to the configuration class Mybatis different databases and different database corresponding to the operation of mapper.

The above configuration tutorial reference south a little rain the blog.

Guess you like

Origin www.cnblogs.com/lwhsummer/p/11223617.html