spring-boot mybadis multiple data source configuration

spring-boot mybadis multiple data source configuration

Strongly recommended: As long as one line of annotation, use mybatis's multiple data sources without any configuration.

github address: gitee.com/xiaojiezhu/...

\

Only one line of annotation is needed to configure multiple data sources of mybadis

This is a mybadis starter based on spring boot

Support multiple data sources

The usage is very simple, first 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 #The size of the idle connection pool 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 #initialization size minIdle: 1 #The size of the idle connection pool maxActive: 50 #Maximum number of activations Copy code

\

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 code

In the above comment, saas is the configuration file above, the name of the data source, followed by the interface package name to be scanned, and multiple input can be separated by commas, followed by the configuration file path of the scanned xml, and it also supports receiving in multiple comments. It is an array, so it supports multiple data sources, except that it can be used without any code

\

The required package depends on  pom.xml

<?xml version="1.0" encoding="UTF-8"?> < 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 code

For detailed use, see the code on the code cloud

Spring boot mybadis multi-data source configuration of pure code configuration

github address: gitee.com/xiaojiezhu/...

The required package depends on  pom.xml

<?xml version="1.0" encoding="UTF-8"?> < 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-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 the 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... 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 code

Directory: xml file a.xml in resources/mapper

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper 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 code

Start class

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 1: Remove the basePackage path test in the configuration and cannot be removed, or it cannot be removed in the case of multiple data sources. You need to configure a package and scan the subpackage. * 2: It is not possible to write all in one class and cannot be read * 3: Annotation class, use class.forName, (Class<? extends Annotation>) Class.forName("com.zxj.ds.mybatis.annotation.SaasDao") * 4: SQL can be written in the configuration file * 5: Do both data sources support transactions? Only one data source supports transactions, that is, the data source with @Primary annotation configured in dataSource * 6: Can the two data sources roll back the transaction together? Only one annotation supports the transaction * 7: Auto-turn hump is ok, but if the hump is set, the hump will be forced to turn. Underscore is not supported */ @SpringBootApplication public class Application { public static void main (String[] args) { SpringApplication.run(Application.class,args); } } Copy code

Change the data source to druid, delete the annotation configuration

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 { //Parameters related to database connection: 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 related parameters: //The maximum time (milliseconds) to wait for a connection from the connection pool, SQLException will occur if the connection is not available for more than this time, default: 30 seconds private long connectionTimeout = 30000 ; //a The maximum duration of the connection idle state (milliseconds), timeout will be released (retired), default: 10 minutes private long idleTimeout = 600000 ; //The life time of a connection (milliseconds), timeout and it will be released if it is not used (retired ), default: 30 minutes, it is recommended to set more than 30 seconds less than the database timeout period, //Refer to the MySQL wait_timeout parameter (show variables like'%timeout%';) private long maxLifetime = 1765000 ; //Maximum allowed in the connection pool Number of connections. Default value: 10; recommended formula: ((core_count * 2) + effective_spindle_count) private int maximumPoolSize = 15 ; @Bean () @Primary public the DataSource DataSource1 () { 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 () { DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driverClassName); ds.setUrl(String.format(jdbcUrl, "saas2" )); ds.setUsername(userName); ds.setPassword(password); return ds; } } Copy code

Create a new MyBatisConfiguration.java file

\

Only one line of annotation is needed to configure multiple data sources of mybadis

This is a mybadis starter based on spring boot

Support multiple data sources

The usage is very simple, first 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.framework.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; /** * Configure SqlSessionFactory: *-Create SqlSessionFactoryBean and specify a dataSource; *-Set up this paging plugin: https://github.com/pagehelper/Mybatis-PageHelper; *-Specify the path of the mapper file; */ @Bean public SqlSessionFactory sqlSessionFactory1 () { return setMapper(ds1); } @Bean public SqlSessionFactory sqlSessionFactory2 () { return setMapper(ds2); } private SqlSessionFactory setMapper (DataSource ds) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(ds); //Paging plugin 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 configuration items org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(); //Automatically convert underscore to camel case //configuration.setMapUnderscoreToCamelCase(true); bean.setConfiguration(configuration); return bean.getObject(); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } } /** * Transaction related configuration * Because there are two data sources, all use ChainedTransactionManager to include two DataSourceTransactionManager together. */ @Override public PlatformTransactionManager annotationDrivenTransactionManager () { DataSourceTransactionManager dtm1 = new DataSourceTransactionManager(ds1); DataSourceTransactionManager dtm2 = new DataSourceTransactionManager(ds2); ChainedTransactionManager ctm = new ChainedTransactionManager(dtm2, dtm1); return ctm; } } Copy 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 package path where dao is located. The path can be separated by commas or semicolons and set multiple *-The Annotation name of the associated annotation on the dao class; *-The above comment is not necessary */ @Bean public MapperScannerConfigurer mapperScannerConfigurer1 () 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 () { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName( "sqlSessionFactory2" ); mapperScannerConfigurer.setBasePackage( "com.zxj.ds.mybatis.dao.saas2" ); //mapperScannerConfigurer.setAnnotationClass(Saas2Dao.class); return mapperScannerConfigurer; } } Copy code

Configuration is complete, starting from the  controller , 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; /** * @Author * @Date 2017/5/4 10:41:42 * Explain the role of this class... */ @Controller public class HelloController { @Autowired private HelloService service; @RequestMapping("/") @ResponseBody public String 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 () { service.b(); return "b" ; } } Copy code

service creates a new   HelloService.java  file

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 () { List<OrderRecord> d = saas2Dao.getOilOrder(); return d; } public List<WeichatAccount> getAccounts () { return saasDao.getAccounts(); } @Transactional public void b () { /* boolean r = saasDao.addApp("002","xxx"); System.out.println(r); throw new RuntimeException("");*/ boolean r = saas2Dao.addStaff( "id1" , "xx" ); throw new RuntimeException( "" ); } } Copy code

Create two packages saas  and  saas2 in Dao respectively  

Create DbSaasDao.java file 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 () ; @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','http://www.kindpetro.com.cn/admin/sqf.apk', '2017-04-18 11:09:49', '2017-04-18 11:09:52', '1, optimize page display;\\r\\n2, fix bug.', '0');\n") boolean addApp ( @Param("id") String id, @Param("name") String name) ; } Copy code

Create 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 () ; @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 code

Create  annotation  package 

Create Saas2Dao.java file

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 code

Create SaasDao.java file

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 code

carry out\

\



\

\