Springboot Integrated MyBatis Multi-data source configuration

Source: Internet
Author: User
Tags db2

One, MySQL's multi-data source configuration 1. Project structure
Package Name Description
Com.kk.configuration Database configuration Layer
Com.kk.testcss.controller Control layer
Com.kk.testcss.dao Database operations layer, divided into two different packages, respectively, operation of data source 1 and data source 2
Com.kk.testcss.service Business Logic Layer
Com.kk.model Entity class
Com.kk.Application Start class
2. Database Configuration

Springboot Master Profile application.properties file Add basic information about the database

#数据源1network.datasource.url=jdbc:mysql://127.0.0.1:3306/db2?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=falsenetwork.datasource.username=rootnetwork.datasource.password=rootnetwork.datasource.driverClassName=com.mysql.jdbc.Driver#数据源2message.datasource.url=jdbc:mysql://127.0.0.1:3306/db2?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=falsemessage.datasource.username=rootmessage.datasource.password=rootmessage.datasource.driverClassName=com.mysql.jdbc.Driver
3. Dependencies that need to be imported

Pom.xml files are as follows

<?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.kk    </groupId> <artifactId>csstestdemo1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>csstestdemo1</name> <description>demo Project for Sp Ring boot</description> <parent> <groupId>org.springframework.boot</groupId> < Artifactid>spring-boot-starter-parent</artifactid> <version>1.5.8.RELEASE</version> &lt ;relativepath/> <!--lookup parent from repository to </parent> <properties> &LT;PROJEC T.build.sourceencoding>utf-8</project.build.sourceencOding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.ve rsion>1.8</java.version> </properties> <dependencies> <dependency> < Groupid>org.springframework.boot</groupid> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-THYMELEAF&LT;/ARTIFAC tid> </dependency> <dependency> <groupid>org.springframework.boot</groupi d> <artifactId>spring-boot-starter-web</artifactId> </dependency> <depend Ency> <groupId>mysql</groupId> <artifactid>mysql-connector-java</artifactid&            Gt <scope>runtime</scope> </dependency> <dependency> <groupid>org.spri Ngframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <s Cope>test</scope> </dependency> <dependency> &LT;GROUPID&GT;ORG.MYBATIS.SPRING.BOOT&L T;/groupid> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0 </version> </dependency> <!--Druid data connection pool dependency cannot support SQL Server 2000--> &LT;DEPENDENCY&G            T <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version&gt            ;1.0.25</version> </dependency> <!--on SQL Server 2000-<dependency> <groupId>com.microsoft</groupId> <artifactId>sql-server</artifactId> &L T;version>1.0.0</version> <scope>system</scope> <systempath>${project.bas Edir}/src/main/resources/lib/mssqlserver2.jar</systempath> </dependency> <!--freemarker front page templates  Dependent-      <dependency> <groupId>org.springframework.boot</groupId> <artifactid>s        pring-boot-starter-freemarker</artifactid> </dependency> </dependencies> <build>                <plugins> <plugin> <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
4. Project Structure

5. Multi-Data Source configuration
    1. To write a configuration class for data source 1
Package Com.konka.configuration;import Com.konka.testcss.utils.initialdatabase;import Org.apache.ibatis.session.sqlsessionfactory;import Org.mybatis.spring.sqlsessionfactorybean;import Org.mybatis.spring.annotation.mapperscan;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.support.pathmatchingresourcepatternresolver;import Org.springframework.jdbc.datasource.datasourcetransactionmanager;import javax.sql.datasource;@ Configuration@mapperscan (basepackages = Com.kk.configuration.NetworkConfig.PACKAGE, Sqlsessionfactoryref = "    Networksqlsessionfactory ") public class Networkconfig {static final String package =" Com.kk.testcss.dao.network ";    Static final String mapper_location = "Classpath:mapper/network/*.xml"; @ValuE ("${network.datasource.driverclassname}") Private String Driverclass;    @Value ("${network.datasource.url}") Private String URL;    @Value ("${network.datasource.username}") private String user;    @Value ("${network.datasource.password}") private String password;  @Bean (name = "Networkdatasource") @Primary public DataSource Networkdatasource () {Druiddatasource DataSource        = new Druiddatasource ();        Datasource.setdriverclassname (Driverclass);        Datasource.seturl (URL);        Datasource.setusername (user);        Datasource.setpassword (password);    return dataSource; } @Bean (name = "Networktransactionmanager") @Primary public Datasourcetransactionmanager Networktransactionmanage    R () {return new Datasourcetransactionmanager (Networkdatasource ()); } @Bean (name = "Networksqlsessionfactory") @Primary public sqlsessionfactory networksqlsessionfactory (@Qualifier ( "Networkdatasource") DataSource Networkdatasource) throws Exception {final Sqlsessionfactorybean sessionfactory = new Sqlsessionfactorybean ();        Sessionfactory.setdatasource (Networkdatasource); Sessionfactory.setmapperlocations (New Pathmatchingresourcepatternresolver (). Getresources (        Com.konka.configuration.NetworkConfig.MAPPER_LOCATION));    return Sessionfactory.getobject (); }}
    1. to write the configuration class for data source 2
Package Com.konka.configuration;import Com.microsoft.jdbcx.sqlserver.sqlserverdatasource;import Org.apache.ibatis.session.sqlsessionfactory;import Org.mybatis.spring.sqlsessionfactorybean;import Org.mybatis.spring.annotation.mapperscan;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.support.pathmatchingresourcepatternresolver;import Org.springframework.jdbc.datasource.datasourcetransactionmanager;import javax.sql.datasource;@ Configuration@mapperscan (basepackages = Com.konka.configuration.MessageConfig.PACKAGE, Sqlsessionfactoryref = "    Messagesqlsessionfactory ") public class Messageconfig {static final String package =" Com.konka.testcss.dao.message ";    Static final String mapper_location = "Classpath:mapper/message/*.xml"; @Value ("${message.datasource.driverclassname} ") Private String Driverclass;    @Value ("${message.datasource.url}") Private String URL;    @Value ("${message.datasource.username}") private String user;    @Value ("${message.datasource.password}") private String password;  @Bean (name = "Messagedatasource") @Primary public DataSource Networkdatasource () {Druiddatasource DataSource        = new Druiddatasource ();        Datasource.setdriverclassname (Driverclass);        Datasource.seturl (URL);        Datasource.setusername (user);        Datasource.setpassword (password);    return dataSource;        } @Bean (name = "Messagetransactionmanager") public Datasourcetransactionmanager Messagetransactionmanager () {    return new Datasourcetransactionmanager (Messagedatasource ()); } @Bean (name = "Messagesqlsessionfactory") public sqlsessionfactory messagesqlsessionfactory (@Qualifier ("MessageData Source ") DataSource Messagedatasource) throws Exception {final Sqlsessionfactorybean sessionfactory = NEW Sqlsessionfactorybean ();        Sessionfactory.setdatasource (Messagedatasource); Sessionfactory.setmapperlocations (New Pathmatchingresourcepatternresolver (). Getresources (        Com.konka.configuration.MessageConfig.MAPPER_LOCATION));    return Sessionfactory.getobject (); }}
    1. @Primary flag This bean is considered first if it is a candidate for several similar beans. When configuring multiple data sources, be aware that you must have a primary data source, with @Primary flag that bean"
    2. @MapperScan scanning Mapper interface and container management
    3. @Value get the KV configuration of the global profile application.properties and assemble it automatically
      Sqlsessionfactoryref indicates that a key is defined, representing a unique sqlsessionfactory instance

Springboot Integrated MyBatis Multi-data source configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.