d之前介绍了Spring Boot 整合mybatis 使用注解方式配置的方式实现增删改查以及一些复杂自定义的sql 语句 。想必大家对spring boot 项目中,如何使用mybatis 有了一定的了解。但在很多业务场景下,我们需要在一个项目中配置多个数据源来实现业务逻辑,例如:现有电商业务,商品和库存数据分别放在不同的数据库中,这就要求我们的系统架构支持同时配置多个数据源实现相关业务操作。那么Spring Boot 如何应对这种多数据源的场景呢?其实,在 Spring Boot 项目中配置多数据源十分便捷。接下来就聊一聊 Spring Boot 整合mybatis 实现多数据源的相关配置。

关于整合mybatis 部分,之前已经介绍过,这里直接讲 Mybatis 多数据源的配置的配置实现,不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html

一、配置数据库

首先在系统配置文件中,需要配置多个数据源,即在application.properties 文件中增加如下配置:

# mybatis 多数据源配置
# 数据库1的配置
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/zwz_test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test1.username = root
spring.datasource.test1.password = root
# 数据库2的配置
spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url = jdbc:mysql://localhost:3306/zwz_test2?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test2.username = root
spring.datasource.test2.password = root

注意:

1、这里配置的是两个一样的数据库zwz_test 和zwz_test2。

2、数据库连接的配置使用jdbc-url , 不是之前的url ,这点需要注意。

二、数据源配置类

1、主数据源配置类

在config 包中,创建 DataSource1Config 类。此类配置主数据源。

package com.weiz.config;

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.Qualifier;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.weiz.mapper.test1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {
@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "test1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name = "test1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

2、配置其他数据源

在config 包中,创建DataSource2Config 类。此类配置其他普通数据源。

package com.weiz.config;

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.Qualifier;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration
@MapperScan(basePackages = "com.weiz.mapper.test2", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {
@Bean(name = "test2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name = "test2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

说明, DataSource1Config 和  DataSource2Config 即是相关的主数据源配置类和普通数据源配置类。

com.weiz.mapper.test1 为 扫描的mapper的路径。

可以看到两个数据源都配置的各自的DataSource、SqlSessionFactory、TransactionManager和SqlSessionTemplate 。

虽然两个类看着差不多,但是需要特别注意以下几点:

  1、主数据源配置需要加@Primary 注解,其他普通数据源不能加这个注解,否则会报错,复制的时候小心。

  2、各个数据源配置的 basePackages 扫描路径需要配置正确。配置错了不会出异常,但是运行的时候,会找错数据库。

3、调用测试

首先,创建com.weiz.mapper.test1 和 com.weiz.mapper.test2 包,将之前的UserMapper ,重名命为User1Mapper 和User2Mapper 复制到相应的包中。

然后,UserServiceImpl 分别注入两个不同的 Mapper,想操作哪个数据源就使用哪个数据源的 Mapper 进行操作处理。

package com.weiz.service.impl;

import com.weiz.mapper.test1.User1Mapper;
import com.weiz.mapper.test2.User2Mapper;
import com.weiz.pojo.User;
import com.weiz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceImpl implements UserService { @Autowired
private User1Mapper user1Mapper; @Autowired
private User2Mapper user2Mapper; @Override
public int saveUser(User user) {
user1Mapper.insert(user);
return user2Mapper.insert(user);
} @Override
public int updateUser(User user) {
user1Mapper.updateByPrimaryKey(user);
return user2Mapper.updateByPrimaryKey(user);
} @Override
public int deleteUser(String userId) {
user1Mapper.deleteByPrimaryKey(userId);
return user2Mapper.deleteByPrimaryKey(userId);
} @Override
public User queryUserById(String userId) {
user1Mapper.selectByPrimaryKey(userId);
return user2Mapper.selectByPrimaryKey(userId);
}
}

这里是一个简单的测试程序,实际项目中是根据实际的业务,调用不同的mapper 实现的,或者通过注解配置,动态切换数据源。

三、测试

启动项目,浏览器中输入如下地址: http://localhost:8088/mybatis/saveuser ,可以看到两个数据库中,都增加了一条用户信息。

数据库 zwz_test 中 用户表sys_user 增加了一条记录。

数据库 zwz_test2 中 用户表sys_user 也增加了一条同样的记录。

四、可能会遇到的坑

1、数据库连接的配置使用jdbc-url , 不是之前的url 。这点需要注意。

2、主数据源配置需要加@Primary 注解,其他普通数据源不能加这个注解,否则会报错,复制的时候小心。

3、各个数据源配置的 basePackages 扫描路径需要配置正确。配置错了不会出异常,但是运行的时候,会找错数据库。

4、如果Mybatis使用的是xml 配置版,xml位置需要在每个config显示置顶位置。

最后

以上,就把Spring Boot整合Mybatis,实现多数据源配置的功能介绍完了。操作看似简单,其实还是得小心仔细。不然很容易出错。

此外配置多数据源之后,还涉及到数据源切换的问题,网上有很多种方法,比较流行的就是druid框架实现多数据源切换。这个后面再讲吧。

还有,这里没有使用事务,如果采用事务需要分别配置每个数据源的事务,并采用事务性注解进行统一管理。这里不细说大家自己研究吧。

这个系列课程的完整源码,也会提供给大家。大家关注我的微信公众号(架构师精进),回复:springboot源码。获取这个系列课程的完整源码。

Spring Boot 入门系列(二十三)整合Mybatis,实现多数据源配置!的更多相关文章

  1. Spring Boot入门系列(十三)如何实现事务

    前面介绍了Spring Boot 中的整合Mybatis并实现增删改查.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1 ...

  2. Spring Boot 2.x基础教程:MyBatis的多数据源配置

    前两天,我们已经介绍了关于JdbcTemplate的多数据源配置以及Spring Data JPA的多数据源配置,接下来具体说说使用MyBatis时候的多数据源场景该如何配置. 添加多数据源的配置 先 ...

  3. Spring Boot入门系列(十七)整合Mybatis,创建自定义mapper 实现多表关联查询!

    之前讲了Springboot整合Mybatis,介绍了如何自动生成pojo实体类.mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能.mybatis 插件自动生成的mappe ...

  4. Spring Boot入门系列(二十)快速打造Restful API 接口

    spring boot入门系列文章已经写到第二十篇,前面我们讲了spring boot的基础入门的内容,也介绍了spring boot 整合mybatis,整合redis.整合Thymeleaf 模板 ...

  5. Spring Boot入门系列(十六)使用pagehelper实现分页功能

    之前讲了Springboot整合Mybatis,然后介绍了如何自动生成pojo实体类.mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能.接下来要说一说Mybatis 的分页 ...

  6. Spring Boot 2.X(二):集成 MyBatis 数据层开发

    MyBatis 简介 概述 MyBatis 是一款优秀的持久层框架,支持定制化 SQL.存储过程以及高级映射.它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简 ...

  7. Spring Boot干货系列:(七)默认日志框架配置

    Spring Boot干货系列:(七)默认日志框架配置 原创 2017-04-05 嘟嘟MD 嘟爷java超神学堂 前言 今天来介绍下Spring Boot如何配置日志logback,我刚学习的时候, ...

  8. Spring Boot2 系列教程 (十三) | 整合 MyBatis (XML 版)

    前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,之前介绍过了 SpringBoot 整合MyBatis 注解版的使用,上一篇介绍过 MyBatis ...

  9. Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

    上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...

随机推荐

  1. Java 给Word添加印章

    一.概述 本文以Java程序代码展示如何给Word文档添加印章,这里添加的印章为.png格式的图片,添加印章即在Word中的指定位置添加印章图片. 基本思路:加载word文档,获取段落,在段落中插入图 ...

  2. C# JSON学习之序列化与反序列化

    在我的个人计划中,学习制作c#下的曲线平台属于下半年的重点.关于前后端的数据传递-json数据的学习很有必要,通过一个例子来加深自己的理解. 新建一个console控制台程序,通过导入NewstonS ...

  3. SQL语句(cmd)

    引言 可视化界面采用的是SQLyog 在SQL语句中--表示单行注释,/**/表示多行注释 命令行操作数据库 启动MySQL服务----net start mysql 连接数据库----mysql - ...

  4. OpenGL学习笔记(四)纹理

    目录 要完成的纹理效果 纹理环绕方式 纹理过滤 多级渐远纹理 加载与创建纹理 stb_image库的使用方法 生成纹理对象 应用纹理 纹理单元 参考资料:OpenGL中文翻译 要完成的纹理效果 纹理是 ...

  5. RAID磁盘阵列和RAID配置

    目录 一.RAID磁盘阵列介绍 二.RAID磁盘阵列分类 2.1.RAID 0(条带化存储) 2.2.RAID 1(镜像存储) 2.3.RAID 5 2.4.RAID 6 2.5.RAID 1+0和0 ...

  6. Java数组05——Arrays类

    Arrays类讲解  package array; ​ import java.util.Arrays; ​ public class ArrayDemon07 {     public static ...

  7. ASP.NET Corec初步使用Quartz.NET

    一.什么是Quartz.NET? Quartz.NET 是一个功能齐全的开源作业调度系统,可用于从最小的应用程序到大型企业系统. Quartz.NET是纯净的,它是一个.Net程序集,是非常流行的Ja ...

  8. 数据库之 MySQL

    MySQL简单入门 数据库这个概念想必大家都听说过,我在这里也简单介绍一下. 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库.每个数据库都有一个或多个不同的 API 用于创建,访 ...

  9. Java线程基础及多线程的实现

    一.进程和线程 1.进程:正在运行的程序         是系统进行资源分配和调用的独立单位         每一个进程都有它自己的内存空间和系统资源 2.线程是进程中的单个顺序控制流,是一条执行路径 ...

  10. Vue2.x响应式原理

    一.回顾Vue响应式用法 ​ vue响应式,我们都很熟悉了.当我们修改vue中data对象中的属性时,页面中引用该属性的地方就会发生相应的改变.避免了我们再去操作dom,进行数据绑定. 二.Vue响应 ...