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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.11.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.gblfy</groupId><artifactId>springboot-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-mybatis</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!--SpringBoot mvc启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Mysql数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><!--lombok 简化java代码--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!--druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><!--SpringBoot test 启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory></resource></resources></build></project>

首先在 application.properties 中配置数据库基本信息,然后提供两个 DataSource 即可

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

然后再提供两个 DataSource,如下:

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configuration
public class DataSourceConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource.one")DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix = "spring.datasource.two")DataSource dsTwo() {return DruidDataSourceBuilder.create().build();}
}

MyBatis 配置
要提供两个 Bean,因此这里两个数据源我将在两个类中分开来配置,首先来看第一个数据源的配置:

mport org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;
import javax.sql.DataSource;@Configuration
@MapperScan(basePackages = "com.gblfy.springboot.mybatis.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MyBatisConfigOne {@Resource(name = "dsOne")DataSource dsOne;@BeanSqlSessionFactory sqlSessionFactory1() {SqlSessionFactory sessionFactory = null;try {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dsOne);sessionFactory = bean.getObject();} catch (Exception e) {e.printStackTrace();}return sessionFactory;}@BeanSqlSessionTemplate sqlSessionTemplate1() {return new SqlSessionTemplate(sqlSessionFactory1());}
}

创建 MyBatisConfigOne 类,首先指明该类是一个配置类,配置类中要扫描的包是 org.javaboy.mybatis.mapper1 ,即该包下的 Mapper 接口将操作 dsOne 中的数据,对应的 SqlSessionFactory 和 SqlSessionTemplate 分别是 sqlSessionFactory1 和 sqlSessionTemplate1,在 MyBatisConfigOne 内部,分别提供 SqlSessionFactory 和 SqlSessionTemplate 即可, SqlSessionFactory 根据 dsOne 创建,然后再根据创建好的SqlSessionFactory 创建一个 SqlSessionTemplate。

这里配置完成后,依据这个配置,再来配置第二个数据源即可:

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;
import javax.sql.DataSource;@Configuration
@MapperScan(basePackages = "com.gblfy.springboot.mybatis.mapper2",sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {@Resource(name = "dsTwo")DataSource dsTwo;@BeanSqlSessionFactory sqlSessionFactory2() {SqlSessionFactory sessionFactory = null;try {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dsTwo);sessionFactory = bean.getObject();} catch (Exception e) {e.printStackTrace();}return sessionFactory;}@BeanSqlSessionTemplate sqlSessionTemplate2() {return new SqlSessionTemplate(sqlSessionFactory2());}
}

好了,这样 MyBatis 多数据源基本上就配置好了,接下来只需要在 org.javaboy.mybatis.mapper1 和 org.javaboy.mybatis.mapper2 包中提供不同的 Mapper,Service 中注入不同的 Mapper 就可以操作不同的数据源。
com.gblfy.springboot.mybatis.mapper1中的 mapper:

import com.gblfy.springboot.mybatis.entity.User;import java.util.List;public interface UserMapperOne{List<User> getAllUser();
}

对应的 XML 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gblfy.springboot.mybatis.mapper1.UserMapperOne"><select id="getAllUser" resultType="com.gblfy.springboot.mybatis.entity.User">select * from user;</select>
</mapper>

com.gblfy.springboot.mybatis.mapper2中的 mapper:

import com.gblfy.springboot.mybatis.entity.User;import java.util.List;public interface UserMapper {List<User> getAllUser();
}

对应的 XML 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gblfy.springboot.mybatis.mapper2.UserMapper"><select id="getAllUser" resultType="com.gblfy.springboot.mybatis.entity.User">select * from user;</select>
</mapper>

实体类:

import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;@Data
public class User implements Serializable {//主键private Long id;//姓名private String name;//年龄private Integer age;//邮箱private String email;//创建时间private LocalDateTime createTime;
}

数据库脚本;
one

DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',create_time DATETIME DEFAULT NULL COMMENT '创建时间',PRIMARY KEY (id)
);DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone', 18, 'test1@gblfy.com','2019-01-11 14:20:20'),
(2, 'Jack', 20, 'test2@gblfy.com','2019-02-05 11:12:22'),
(3, 'Tom', 28, 'test3@gblfy.com','2019-02-14 08:31:16'),
(4, 'Sandy', 21, 'test4@gblfy.com','2019-01-14 09:15:15'),
(5, 'Billie', 24, 'test5@gblfy.com','2019-01-14 09:48:16');

two

DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',create_time DATETIME DEFAULT NULL COMMENT '创建时间',PRIMARY KEY (id)
);DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone2', 18, 'test1@gblfy.com','2019-01-11 14:20:20'),
(2, 'Jack2', 20, 'test2@gblfy.com','2019-02-05 11:12:22'),
(3, 'Tom2', 28, 'test3@gblfy.com','2019-02-14 08:31:16'),
(4, 'Sandy2', 21, 'test4@gblfy.com','2019-01-14 09:15:15'),
(5, 'Billie2', 24, 'test5@gblfy.com','2019-01-14 09:48:16');

写一个测试controller

import com.gblfy.springboot.mybatis.entity.User;
import com.gblfy.springboot.mybatis.mapper1.UserMapperOne;
import com.gblfy.springboot.mybatis.mapper2.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class PageController {@Autowiredprivate UserMapperOne userMapperOne;@Autowiredprivate UserMapper userMapper;@GetMapping("/one")public List<User> getOneList() {return userMapperOne.getAllUser();}@GetMapping("/two")public List<User> getTwoList() {return userMapper.getAllUser();}
}

启动项目:
依次访问
http://localhost:8080/one

http://localhost:8080/two

Spring Boot2 整合 MyBatis 多数据源相关推荐

  1. Spring Boot整合Jpa多数据源

    Spring Boot整合Jpa多数据源 本文是Spring Boot整合数据持久化方案的最后一篇,主要和大伙来聊聊Spring Boot整合Jpa多数据源问题.在Spring Boot整合JbdcT ...

  2. Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

    第一种:使用配置类的方式: 项目结构 xml依赖: <?xml version="1.0" encoding="UTF-8"?> <proje ...

  3. spring boot整合mybatis步骤

    spring boot整合mybatis步骤 官方说明:MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot 其 ...

  4. Spring Boot 整合MyBatis(23)

    Spring Boot 整合MyBatis Spring Boot 整合 Druid 引入依赖 配置 application.yml pring Boot 整合 tk.mybatis 引入依赖 配置 ...

  5. 干货必看|Spring Boot整合MyBatis框架详解

    在开发中,我们通常会对数据库的数据进行操作,Sprirng Boot对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持.所以今天壹哥就给大家讲解一下,如何在SpringBoot环境中整合 ...

  6. Spring Boot整合Mybatis【超详细】

    pring Boot整合Mybatis 配置文件形式 pom.xml 配置数据源 UserMapper.xml UserMapper 配置springboot整合mybatis 在运行类上添加@Map ...

  7. 2021-5-10:Spring Boot整合MyBatis

    Spring Boot整合MyBatis Spring Boot 整合MyBatis (一)基础环境搭建 1.数据准备 创建数据库.数据表并插入一定的数据 (1)创建博客数据库blog 在Navica ...

  8. Spring Boot 教程(三): Spring Boot 整合Mybatis

    教程简介 本项目内容为Spring Boot教程样例.目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中.如您觉得该项目对您有用,欢迎点击收藏和点赞按钮, ...

  9. spring boot 整合mybatis 无法输出sql的问题

    使用spring boot整合mybatis,测试功能的时候,遇到到了sql问题,想要从日志上看哪里错了,但是怎么都无法输出执行的sql,我使用的是log4j2,百度了一下,很多博客都说,加上下面的日 ...

最新文章

  1. 1.72java8_JDK 1.7 1.8 新特性
  2. 运维开发学go还是python_运维工程师是要学python还是学go那?
  3. 【SpringBoot集成ElasticSearch 02】Java HTTP Rest client for ElasticSearch Jest 客户端集成(配置+增删改查测试源码)【推荐使用】
  4. Android Loader 异步加载详解二:探寻Loader内部机制
  5. Redis中的淘汰策略
  6. Windows Server 2012 新特性:IPAM的配置
  7. 【操作系统】Semaphore处理吸烟者问题
  8. c语言三个月兴业,c语言输出2015年日历,要求三个月在一行...
  9. 如何使用fiddler 4进行手机模拟器抓包详细教程
  10. poj 3007 stl
  11. uva 473 - Raucous Rockers(dp)
  12. css 友情链接效果,常用友情链接代码(带样式)
  13. 天天在做大数据,你的时间都花在哪了
  14. BootLoader有什么作用?
  15. 数据挖掘课程笔记--分类(4)朴素贝叶斯
  16. 事理图谱-下一代知识图谱
  17. 【设计模式实战】简单工厂、工厂方法、抽象工厂:原理篇
  18. 2018华为校招机试题目练习
  19. 2013中国域名注册商报告:万网新增15.6万域名
  20. C/C++ 数字1234,能组成多少个互不相同且无重复的三位数数字。

热门文章

  1. GC算法-分代垃圾回收
  2. TextRank、BM25算法提取关键字、文章自动摘要优秀文章保存
  3. equalsignorecase用法
  4. 树结构练习——判断给定森林中有多少棵树
  5. Elasticsearch生态技术峰会 | 阿里云Elasticsearch云原生内核
  6. 投入20亿,赋能1万家,阿里云正式启动云原生合作伙伴计划
  7. 如何为Kubernetes实现原地升级
  8. AliOS Things声源定位应用演示
  9. 基于PCDN技术的无延时直播方案
  10. 云HBase小组成功抢救某公司自建HBase集群,挽救30+T数据