Strongly recommended: One line of comment, use mybatis multi-data source, no configuration required.

Making address: gitee.com/xiaojiezhu/…

\

With a single line of annotations, you can configure multiple data sources for MyBadis

This is a Starter for Mybadis based on Spring Boot

Support for multiple data sources

To use it, define some configuration files and put them in application.yml

mysql: server: saas: url: "jdbc:mysql://localhost:3306/saas? useUnicode=true&characterEncoding=utf8" username: root password: 123 driverClassName: Com.mysql.jdbc.driver initialSize: 1 # Initialization size minIdle: 1 # Idle connection pool size maxActive: 50 # Maximum number of activations saAS2: URL: "jdbc:mysql://localhost:3306/saas2? useUnicode=true&characterEncoding=utf8" username: root password: 123 driverClassName: Com.mysql.jdbc.driver initialSize: 1 # initialSize minIdle: 1 # size of the free connection pool maxActive: 50 # maximum number of activationsCopy the code

\

The main method

@MyBadisLoader({"saas = com.llc.admin.web.dao.saas = classpath:mapper/*xml" , 
                "saas2 = com.llc.admin.web.dao.saas2 = classpath:mapper/*.xml,classpath:mapper/user/*.xml"})
@SpringBootApplication
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class,args);
    }
}
Copy the code

The annotation above the saas is above the configuration file, the data source name, followed by scanning interface package name, you can use a comma to separate into multiple, is to scan the XML configuration file path, then followed by also received support multiple annotation is an array, so support multiple data sources, but does not require any code can be used

\

Required package dependenciespom.xml


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xiaojiezhu.mybadis.starter</groupId>
<artifactId>mybadis-starter</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.4.7. RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.27</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
</dependencies>
</project>
Copy the code

\

Copy the code

Detailed use of code on the code cloud

Pure code configuration for Spring Boot Mybadis multi-source configuration

Making address:Gitee.com/xiaojiezhu/…

Required package dependenciespom.xml


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>datasource-mybatis</groupId>
    <artifactId>ds-mybatis</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>com.framework.sass.service</groupId>
        <artifactId>service-root</artifactId>
        <version>1.0</version>
    </parent>

    <dependencies>
        <! -- Begin of DB related -->
        <dependency> <! -- for ChainedTransactionManager configuration -->
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency> <! -- exclude default JDBC configuration -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <! -- Other packages in the same project... Start - >
        <dependency>
            <groupId>com.framework.recWeiMsg</groupId>
            <artifactId>msg-message</artifactId>
            <version>1.0</version>
        </dependency>
<! -- <dependency> <groupId>com.framework.recWeiMsg</groupId> <artifactId>msg-commons</artifactId> <version>1.0</version> </dependency>-->
<! -- <dependency> <groupId>com.framework. RecWeiMsg </groupId> <artifactId>msg-weichat</artifactId> <version>1.0</version> </dependency>-->
        <! -- Other packages in the same project... The end -- -- >

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency> <! Mybatis paging plugin -->
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

    </dependencies>


</project>
Copy the code

Directory: resources/ mapper XML file a.xml


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zxj.ds.mybatis.dao.saas2.DbSaas2Dao">

    <select id="getOilOrder" resultType="com.framework.msg.db.businessTransaction.OrderRecord">
        select * from orderRecord
    </select>
</mapper>
Copy the code

Start the class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * * * 1: * 3: class <? ForName: (class <? Extends the Annotation >) Class. Class.forname (" com. ZXJ. Ds. Mybatis. The Annotation. SaasDao ") * 4: can write SQL in the configuration file * 5: if two data sources support transactions Only one dataSource supports transactions, and that is the dataSource configuration@PrimaryNote data source * 6: two data sources can be rolled back together transaction only one annotation supports transaction * 7: automatic hump can be set, but set the hump to force the hump. Underline */ is not supported
@SpringBootApplication
public class Application {
    public static void main(String[] args) { SpringApplication.run(Application.class,args); }}Copy the code

Change the data source to druid and remove the configuration of annotations

DataSourceConfiguration.java

package com.zxj.ds.mybatis.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/** * Created by Administrator on 2017/5/4. */
@Configuration
public class DataSourceConfiguration {
    // Database connection parameters:
    private String driverClassName = "com.mysql.jdbc.Driver";
    private String jdbcIpPort = "3306";
    private String jdbcUrl = "jdbc:mysql://server1:3306/%s? useUnicode=true&characterEncoding=utf8";
    private String userName = "root";
    private String password = "123";

    // Connection pool parameters:
    // The maximum length of time (milliseconds) to wait for a connection from the connection pool, after which a connection is not available SQLException occurs. Default :30 seconds
    private long connectionTimeout = 30000;
    // Maximum idle time of a connection (ms). Then it will be released. Default :10 minutes
    private long idleTimeout = 600000;
    // The lifetime of a connection (ms). If it has timed out and not been used, it will be released. Default :30 minutes.
    // refer to MySQL wait_timeout (show variables like '%timeout%';)
    private long maxLifetime = 1765000;
    // The maximum number of connections allowed in the pool. Default value: 10. Recommended formula :(core_count * 2) + effective_spindle_count)
    private int maximumPoolSize = 15;


    @Bean()
    @Primary
    public DataSource dataSource1(a){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUrl(String.format(jdbcUrl, "saas"));
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }

    @Bean()
    public DataSource dataSource2(a){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUrl(String.format(jdbcUrl, "saas2"));
        ds.setUsername(userName);
        ds.setPassword(password);
        returnds; }}Copy the code

New MyBatisConfiguration. Java file

\

With a single line of annotations, you can configure multiple data sources for MyBadis

This is a Starter for Mybadis based on Spring Boot

Support for multiple data sources

To use it, define some configuration files and put them in application.yml

package com.zxj.ds.mybatis.configuration;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/** * Created by Administrator on 2017/5/4. */
@Configuration
@EnableTransactionManagement
@AutoConfigureAfter(DataSourceConfiguration.class)
public class MyBatisConfiguration implements TransactionManagementConfigurer {
    private final static Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);

    @Resource(name = "dataSource1")
    private DataSource ds1;
    @Resource(name = "dataSource2")
    private DataSource ds2;


    SqlSessionFactory: * - Create a SqlSessionFactoryBean and specify a dataSource; * - set the paging plug-in: https://github.com/pagehelper/Mybatis-PageHelper; * - Specifies the mapper file path; * /
    @Bean
    public SqlSessionFactory sqlSessionFactory1(a) {
        return setMapper(ds1);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory2(a) {
        return setMapper(ds2);
    }





    private SqlSessionFactory setMapper(DataSource ds) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);

        // Paging plug-in
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("dialect"."mysql");
        properties.setProperty("reasonable"."false");
        properties.setProperty("pageSizeZero"."true");
        pageHelper.setProperties(properties);
        bean.setPlugins(new Interceptor[]{pageHelper});

        try {
            // Specify the mapper XML directory
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            // Set the configuration item
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            // Automatically convert underscores to humps
// configuration.setMapUnderscoreToCamelCase(true);
            bean.setConfiguration(configuration);
            return bean.getObject();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw newRuntimeException(e); }}/ * * * * Transaction related configuration because there are two data sources, all use ChainedTransactionManager include two DataSourceTransactionManager together. * /
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager(a) {
        DataSourceTransactionManager dtm1 = new DataSourceTransactionManager(ds1);
        DataSourceTransactionManager dtm2 = new DataSourceTransactionManager(ds2);

        ChainedTransactionManager ctm = new ChainedTransactionManager(dtm2, dtm1);
        returnctm; }}Copy the code

Create MyBatisScanner. Java

\

package com.zxj.ds.mybatis.configuration;

import com.zxj.ds.mybatis.annotation.Saas2Dao;
import com.zxj.ds.mybatis.annotation.SaasDao;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.annotation.Annotation;

/** * Created by Administrator on 2017/5/4. */
@Configuration
@AutoConfigureAfter(MyBatisConfiguration.class)
public class MyBatisScanner {

    /** * - set SqlSessionFactory; * - Set the dao's package path, which can be separated by commas or semicolons. Set multiple * - Annotation Annotation names on the DAO class; * - The above comments do not need */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer1(a) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1");
        mapperScannerConfigurer.setBasePackage("com.zxj.ds.mybatis.dao.saas");
        //mapperScannerConfigurer.setAnnotationClass((Class<? extends Annotation>) Class.forName("com.zxj.ds.mybatis.annotation.SaasDao"));
        return mapperScannerConfigurer;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer2(a) {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory2");
        mapperScannerConfigurer.setBasePackage("com.zxj.ds.mybatis.dao.saas2");
        //mapperScannerConfigurer.setAnnotationClass(Saas2Dao.class);
        returnmapperScannerConfigurer; }}Copy the code

The configuration is completecontrollerStart with specific use

Create HelloController. Java

\

package com.zxj.ds.mybatis.controller;

import com.framework.msg.db.WeichatAccount;
import com.framework.msg.db.businessTransaction.OrderRecord;
import com.zxj.ds.mybatis.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/ * * *@AuthorZhu Xiaojie *@Date2017/5/4 10:41:42 * Explain what this class does... * /
@Controller
public class HelloController {
    @Autowired
    private HelloService service;

    @RequestMapping("/")
    @ResponseBody
    public String a(a){
        List<Map<String,Object>> users = service.getUsers();
        System.out.println(users);

        List<OrderRecord> orders = service.getOilOrder();
        System.out.println(orders);

        List<WeichatAccount> accounts = service.getAccounts();
        System.out.println(accounts);

        return "SUCCESS";
    }

    @ResponseBody
    @RequestMapping("/b")
    public String b(a){
        service.b();
        return "b"; }}Copy the code

The service of newHelloService.javafile

package com.zxj.ds.mybatis.service;

import com.framework.msg.db.WeichatAccount;
import com.framework.msg.db.businessTransaction.OrderRecord;
import com.zxj.ds.mybatis.dao.saas2.DbSaas2Dao;
import com.zxj.ds.mybatis.dao.saas.DbSaasDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service
public class HelloService {
    @Autowired
    private DbSaasDao saasDao;
    @Autowired
    private DbSaas2Dao saas2Dao;
    public List<Map<String, Object>> getUsers() {
        List<Map<String, Object>> datas = saasDao.getUsers();
        return datas;
    }

    public List<OrderRecord> getOilOrder(a) {
        List<OrderRecord> d = saas2Dao.getOilOrder();
        return d;
    }

    public List<WeichatAccount> getAccounts(a) {
        return saasDao.getAccounts();
    }

    @Transactional
    public void b(a) {
/* boolean r = saasDao.addApp("002","xxx"); System.out.println(r); throw new RuntimeException(""); * /

        boolean r = saas2Dao.addStaff("id1"."xx");
        throw new RuntimeException(""); }}Copy the code

Create two packages separately in Daosaas 和 saas2 

Create dbSAasdao.java files in saas

package com.zxj.ds.mybatis.dao.saas;


import com.framework.msg.db.WeichatAccount;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

//@SaasDao
@Mapper
public interface DbSaasDao {

    @Select("select * from weichat_user limit 50")
    List<Map<String, Object>> getUsers();

    @Select("select * from weichat_account limit 50")
    List<WeichatAccount> getAccounts(a);

    @Insert("INSERT INTO `saas`.`app_version` (`id`, `name`, `version`, `can_use_version`, `update_url`, `create_time`, ` update_time `, ` desc `, ` fileSize `) VALUES (# # {id}, {name}, '1.0.4', '1.0.3, 11:09:49 'http://www.kindpetro.com.cn/admin/sqf.apk', '2017-04-18', '2017-04-18 11:09:52', '1, optimize the page shows; \\r\ n2, fix the Bug. ', '0'); \n")
    boolean addApp(@Param("id") String id,@Param("name") String name);
}
Copy the code

Create the dbSAAS2dao.java file in saAS2

package com.zxj.ds.mybatis.dao.saas2;


import com.framework.msg.db.businessTransaction.OrderRecord;
import com.zxj.ds.mybatis.annotation.Saas2Dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
//@Repository
public interface DbSaas2Dao {

    List<OrderRecord> getOilOrder(a);

    @Insert("INSERT INTO `saas2`.`staff` (`id`, `name`, `appid`, `openid`, `create_time`) VALUES (#{id},#{name}, 'wx2e9a7946612800c5', 'oZnKxwb6QKhv8xNN0of3eAvEd6mM', '2016-12-15 15:04:48'); \n")
    boolean addStaff(@Param("id") String id,@Param("name") String name);
}
Copy the code

createannotation 包 

createSaas2Dao.javafile

package com.zxj.ds.mybatis.annotation;

import java.lang.annotation.*;

/** * connect to SAAS2 database */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Saas2Dao {
}
Copy the code

createSaasDao.javafile

package com.zxj.ds.mybatis.annotation;

import java.lang.annotation.*;

/** * Connect to SAAS library */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface SaasDao {
}
Copy the code

Complete the \

\




\

\