SpringBoot integrates MyBatis and Druid to configure multiple data sources

Posted by pkedpker on Tue, 30 Jul 2019 22:24:17 +0200

Preface

Because the project requires that three data sources be used simultaneously in two projects, and then it's a toss-and-roll. I have seen many cases from the internet, but there are more or less problems. MyBatis, for example, can only be developed with annotations, not configurations. I think the pit-free version, try to be more detailed.

directory structure

Major Dependence

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--    druid Connection pool  -->        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

<!--  Paging plug-in, try high version and spring-boot-starter-pagehalper All startup failures     -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

Add static resource scanning to the <build> tag of pom.xml:

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

configuration file

application.yml configuration

The configuration of data source is given.

spring: 
  datasource:
    pigxpf:
      type: com.alibaba.druid.pool.DruidDataSource
      
      # Note that jdbc is used here when configuring multiple data sources-url,Driver name needs to be used driver-class-name
      jdbc-url: jdbc:mysql://localhost:3306/pf?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

    pigxhr:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:mysql://localhost:3306/hr?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis configuration is in resources/mybatis/mabatis-config.xml The configuration here does not automatically scan.
mybatis:
  # Loading global configuration files
  configLocation: classpath:mybatis/mybatis-config.xml

mybatis-config configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- Open Hump Matching -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- This configuration enables global mappers to enable or disable caching. The default value of the system istrue,Setting up just to show off -->
        <setting name="cacheEnabled" value="true" />
        <!-- Globally enable or disable lazy loading. When disabled, all associated objects are loaded immediately. The default value of the system istrue,Setting up just to show off -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- Multiple result sets are allowed or not to be returned from a single statement (requiring appropriate drivers). The default value of the system istrue,Setting up just to show off -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--Use column labels instead of column names. Different drivers behave differently in this convenience. Reference to driver documentation or adequate testing are two ways to determine the driver used. The default value of the system istrue,Setting up just to show off -->
        <setting name="useColumnLabel" value="true" />
        <!--allow JDBC Support generated keys. A suitable driver is needed. If set to true This setting forces the generated keys to be used, although some drivers refuse compatibility, they are still valid (e.g.
            Derby).  The default value of the system isfalse,Setting up just to show off -->
        <setting name="useGeneratedKeys" value="false" />
        <!--Configure the default executor. SIMPLE There is nothing special about the actuator. REUSE The executor reuses the preprocessing statement. BATCH Executor reuse statements and batch update system defaults are SIMPLE,Setting up just to show off -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--Set a timeout, which determines the time the driver waits for a database response. The default value of the system is null,Setting up just to show off -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>

    <!-- jPaginate -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- Database dialect -->
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <!-- Set totrueWhen using RowBounds Paging will proceed count The query will query the total number. -->
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

Application.java Startup Class

I can use anything here without moving. Some blogs say to cancel automatic scanning, because automatic scanning only loads a data source.

Configuration class

DataSourceConfig.java

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;


/**
 * @author: litblue
 * @Time : 2019/7/28 10:38
 * @Email: litblue@163.com
 * No perfunctory, no slack
 *
 * Manual configuration of data sources
 *
 */

@Configuration
public class DataSourceConfig {

    @Bean(name = "pigxpfDatasource")
    @Primary   /*  Major data sources */
    @ConfigurationProperties(prefix = "spring.datasource.pigxpf")
    public DataSource pigxpfDatasource(){
        return DataSourceBuilder.create().build();
    }

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

MyBatisPigxpfConfig.java

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;


/**
 * @author: litblue
 * @Time : 2019/7/28 10:53
 * @Email: litblue@163.com
 * No perfunctory, no slack
 */

@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxpfConfig {

    @Autowired
    @Qualifier("pigxpfDatasource")
    private DataSource pigxpfSource;

    // Loading configuration files
    @Value("${mybatis.configLocation}")
    private String configLocation;


    @Bean(name="pigxpfSqlFactory")
    @Primary
    public SqlSessionFactory pigxpfSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(pigxpfSource);
        // Configuration type aliases
        factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
        // Configure the scan of mapper to find all mapper.xml Mapping Files
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);

        // Loading configuration files
        factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));

        return factoryBean.getObject();
    }

    @Bean(name="pigxpfSqlFactory")
    @Primary
    public SqlSessionTemplate pigxpfSqlSessionTemplate() throws Exception{
        SqlSessionTemplate template = new SqlSessionTemplate(pigxpfSqlSessionFactory());
        return template;
    }
}

MyBatisPigxhrConfig.java

This is the same as above, except that the @Primary annotation is not required.

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author: litblue
 * @Time : 2019/7/28 11:26
 * @Email: litblue@163.com
 * No perfunctory, no slack
 */

@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxhrConfig {

    @Autowired
    @Qualifier("pigxhrDatasource")
    private DataSource pigxhrSource;

    @Value("${mybatis.configLocation}")
    private String configLocation;

    @Bean(name="pigxhrSqlFactory")
    public SqlSessionFactory pigxhrSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(pigxhrSource);
        // Configuration type aliases
        factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
        // Configure the scan of mapper to find all mapper.xml Mapping Files
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);

        // Loading configuration files
        factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));

        return factoryBean.getObject();
    }

    @Bean(name="pigxhrSqlFactory")
    public SqlSessionTemplate pigxhrSqlSessionTemplate() throws Exception{
        SqlSessionTemplate template = new SqlSessionTemplate(pigxhrSqlSessionFactory());
        return template;
    }
}

Operation results

Last

The monitoring of Druid has not yet been configured, nor is it known what to do. It will be updated later.

Topics: Mybatis Spring JDBC MySQL