SpringBoot 可以支持多数据源,这是一个非常值得学习的功能,但是从现在主流的微服务的架构模式中,每个应用都具有唯一且准确的功能,多数据源的需求很难用到,考虑到实际情况远远比理论复杂的多,这里还是深入学习一个Mybatis的多数据源的配置,代码偏向于实战,提供Git地址,以供下载测试.https://gitee.com/zhoutao825638/Sprinboot_mybatis_ds.git

数据库脚本

我们首先声明记录一下数据库脚本创建了两个数据库,test1和test2 ,并且分别在不同的数据库中创建了student和lesson表.

CREATE DATABASE `test1` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;  ;
USE `test1`;
CREATE TABLE `student`(
`id` VARCHAR(12) PRIMARY KEY,
`name` VARCHAR(36) NOT NULL ,
`age` INTEGER DEFAULT 0
); -- 插入数据
INSERT INTO test1.student (id, name, age) VALUES ('1', '张梦为', 1);
INSERT INTO test1.student (id, name, age) VALUES ('2', '上官婉儿', 2);
INSERT INTO test1.student (id, name, age) VALUES ('3', '唐因', 2); CREATE DATABASE `test2` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; ;
USE `test2`;
CREATE TABLE `lesson`(
`id` VARCHAR(12) PRIMARY KEY,
`name` VARCHAR(36) NOT NULL ,
`credit` FLOAT DEFAULT 0,
`teacher` VARCHAR(36) DEFAULT 0
);
-- 插入数据
INSERT INTO test2.lesson (id, name, credit, teacher) VALUES ('1', '大学物理', 5, '张思瑞');
INSERT INTO test2.lesson (id, name, credit, teacher) VALUES ('2', '高等数学', 5, '李佛');

创建Spring 应用

使用IDEA 可以非常简单的创建一个应用,这里我使用了Gradle构建项目,其依赖如下:

lombok 是一个不错的插件,推荐使用,如果不使用lombok的话,下面的代码需要添加set/get方法

    compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.springframework.boot:spring-boot-starter-web')

配置完成之后,在应用的入口中,我们需要修改一下

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

这是因为SpringBoot会自动根据依赖来自动配置,但是我们的数据源配置被我们自己自定义配置了,此时SpringBoot 无法完成自动化配置,因此就会报错,所以此处我们需要排除DataSourceAutoConfiguration的自动配置.

配置数据源

这里我们配置来两个数据源 一个是test1,一个test2,修改application.properties文件


-- 数据源 Frist
spring.datasource.first.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.first.username=root
spring.datasource.first.password=
spring.datasource.first.driverClassName=com.mysql.jdbc.Driver -- 数据源 Second
spring.datasource.second.url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
spring.datasource.second.username=root
spring.datasource.second.password=
spring.datasource.second.driverClassName=com.mysql.jdbc.Driver

创建配置文件封装类

为了更合理的使用配置文件,这里我们没有使用之前的@Value,而是自己封装一个PropertiesConfig类对象.如下

@Data注解需要添加Lombok插件并开启,需要不想安装的话,请为下面的四个成员变量提供set/get方法即可

数据源First配置文件封装

package com.zhoutao123.springboot.muldatasources.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.first")
public class FirstDataBaseProperties {
String url;
String username;
String password;
String driverClassName;
}

数据源Second配置文件封装

package com.zhoutao123.springboot.muldatasources.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.second")
public class SecondDataBaseProperties {
String url;
String username;
String password;
String driverClassName;
}

完成数据源配置

这里需要完成DataSource/SqlSessionFactory/SessionTemp等对象的注入,需要注意的是,不管配置多少个数据源,其中的一个数据源配置的Bean必须使用@Primary完成注解.

下面是两个数据源的配置,其中First使用了@Primary注解

MapperScan注解的basePackages 表示了其目录下的Mapper使用文件使用该数据源,如FirstDataSource中表示com.zhoutao123.springboot.muldatasources.mapper.first下的Maper文件将使用FirstDataSource.

package com.zhoutao123.springboot.muldatasources.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.Autowired;
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.zhoutao123.springboot.muldatasources.mapper.first",sqlSessionTemplateRef ="firstSqlSessionTemplate")
public class FirstDataSourceConfig { @Autowired
private FirstDataBaseProperties prop; // 创建数据源
@Bean(name = "firstDS")
@ConfigurationProperties(prefix = "spring.datasource.first")
@Primary
public DataSource getFirstDataSource() {
DataSource build = DataSourceBuilder.create()
.driverClassName(prop.driverClassName)
.url(prop.url)
.username(prop.username)
.password(prop.password)
.build();
return build;
} // 创建SessionFactory
@Bean(name = "firstSqlSessionFactory")
@Primary
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDS") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} // 创建事务管理器 @Bean("firstTransactionManger")
@Primary
public DataSourceTransactionManager firstTransactionManger(@Qualifier("firstDS") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
} // 创建SqlSessionTemplate @Bean(name = "firstSqlSessionTemplate")
@Primary
public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
} private Class getType(String type) {
try {
return Class.forName(type);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
} }

以及第二个数据源的配置

package com.zhoutao123.springboot.muldatasources.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.Autowired;
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.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration
@MapperScan(basePackages = "com.zhoutao123.springboot.muldatasources.mapper.second",sqlSessionTemplateRef ="secondSqlSessionTemplate")
public class SecondDataSourceConfig { @Autowired
private SecondDataBaseProperties prop; // 创建数据源
@Bean(name = "secondDS")
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource getSecondDataSource() {
DataSource build = DataSourceBuilder.create()
.driverClassName(prop.driverClassName)
.url(prop.url)
.username(prop.username)
.password(prop.password)
.build();
return build;
} // 创建SessionFactory
@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDS") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} // 创建事务管理器 @Bean("secondTransactionManger")
public DataSourceTransactionManager secondTransactionManger(@Qualifier("secondDS") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
} // 创建SqlSessionTemplate @Bean(name = "secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
} private Class getType(String type) {
try {
return Class.forName(type);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}

实现Mapper

根据数据源配置的MappScan目录来创建测试Mapper,代码如下,注意包名,放在正确的位置上.

返回模型

这里写了两个数据库映射模型,用于接受数据库数据,比较简单.

package com.zhoutao123.springboot.muldatasources.dao;

import lombok.Data;
import lombok.experimental.Accessors; @Data
@Accessors(chain = true)
public class Lesson { private String id; private String name; private String teacher; private float credit;
}
package com.zhoutao123.springboot.muldatasources.dao;

import lombok.Data;
import lombok.experimental.Accessors; @Data
@Accessors(chain = true)
public class Student { private String id; private String name; private String age;
}

创建映射Mapper

package com.zhoutao123.springboot.muldatasources.mapper.first;

import com.zhoutao123.springboot.muldatasources.dao.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper
public interface StudentMapper { // 查询全部的学生
@Select("SELECT * FROM student;")
List<Student> getAllStudent(); }
package com.zhoutao123.springboot.muldatasources.mapper.second;

import com.zhoutao123.springboot.muldatasources.dao.Lesson;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper
public interface LessonMapper { // 查询全部的课程
@Select("SELECT * FROM lesson;")
List<Lesson> getAllLesson(); }

测试接口

这里为了方便,写了一个测试接口和Application放在一起的,同时考虑到这边学习的主要目标是多数据源的配置,就没有Service层,Controller直接调用Mapper,真实项目不要这么写哈.

package com.zhoutao123.springboot.muldatasources;

import com.zhoutao123.springboot.muldatasources.config.FirstDataSourceConfig;
import com.zhoutao123.springboot.muldatasources.config.SecondDataSourceConfig;
import com.zhoutao123.springboot.muldatasources.dao.Lesson;
import com.zhoutao123.springboot.muldatasources.dao.Student;
import com.zhoutao123.springboot.muldatasources.mapper.first.StudentMapper;
import com.zhoutao123.springboot.muldatasources.mapper.second.LessonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import java.security.PublicKey;
import java.util.List; // 排除数据源的自动配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@RestController
public class MuldatasourcesApplication { @Autowired
private StudentMapper studentMapper; @Autowired
private LessonMapper lessonMapper; public static void main(String[] args) {
SpringApplication.run(MuldatasourcesApplication.class, args);
} @GetMapping("/student")
public List<Student> studentList(){
return studentMapper.getAllStudent();
} @GetMapping("/lesson")
public List<Lesson> lessonList(){
return lessonMapper.getAllLesson();
}
}

测试结果

可以看到不同的数据库的数据被查询出来了,实现了多数据源的切换,此处的效果和数据库的读写分离有类似的效果,可以参考分析,学习.

SpringBoot+MyBatis配置多数据源的更多相关文章

  1. springboot + mybatis配置多数据源示例

    转:http://www.jb51.net/article/107223.htm 在实际开发中,我们一个项目可能会用到多个数据库,通常一个数据库对应一个数据源. 代码结构: 简要原理: 1)Datab ...

  2. SpringBoot MyBatis 配置多数据源 (静态多个)

    转载地址:https://www.jianshu.com/p/118ca1d5ecf9?utm_campaign=haruki&utm_content=note&utm_medium= ...

  3. SpringBoot集成Mybatis配置动态数据源

    很多人在项目里边都会用到多个数据源,下面记录一次SpringBoot集成Mybatis配置多数据源的过程. pom.xml <?xml version="1.0" encod ...

  4. springboot入门系列(四):SpringBoot和Mybatis配置多数据源连接多个数据库

    SpringBoot和Mybatis配置多数据源连接多个数据库 目前业界操作数据库的框架一般是 Mybatis,但在很多业务场景下,我们需要在一个工程里配置多个数据源来实现业务逻辑.在SpringBo ...

  5. springboot和mybatis 配置多数据源

    主数据源(由于代码没有办法复制的原因,下面图片和文字不一致) package com.zhianchen.mysqlremark.toword.config;import com.zaxxer.hik ...

  6. Spring Boot + Mybatis 配置多数据源

    Spring Boot + Mybatis 配置多数据源 Mybatis拦截器,字段名大写转小写 package com.sgcc.tysj.s.common.mybatis; import java ...

  7. spring+myBatis 配置多数据源,切换数据源

    注:本文来源于  tianzhiwuqis <spring+myBatis 配置多数据源,切换数据源> 一个项目里一般情况下只会使用到一个数据库,但有的需求是要显示其他数据库的内容,像这样 ...

  8. SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页

    SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了. ...

  9. springboot+mybatis集成多数据源MySQL/Oracle/SqlServer

    日常开发中可能时常会遇到一些这样的需求,业务数据库和第三方数据库,两个或多个数据库属于不同数据库厂商,这时候就需要通过配置来实现对数据库实现多源处理.大致说一下我的业务场景,框架本身是配置的sprin ...

随机推荐

  1. Linux挖矿病毒 khugepageds详细解决步骤

    一.背景 最近公司一台虚拟机被攻击,其中一种挖矿病毒.会伪CPU数.即如果用top命令只能看到一个cpu.并且负载不高.实际上整个负载300%以上,及时定时任务关掉也不起作用. 二.言归正传开始干掉这 ...

  2. 设计模式 | 装饰模式(decorator)

    定义: 装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能.它是通过创建一个包装对象,也就是装饰来包裹真实的对象. 结构:(书中图,侵删) 一个被装饰接口类:从具体类中抽象出来, ...

  3. Vue基本使用

    Vue.js是一款流行的开源JavaScript前端框架,旨在更好地组织与简化Web开发.Vue所关注的核心是MVC模式中的视图层,同时,它也能方便地获取数据更新,并通过组件内部特定的方法实现视图与模 ...

  4. 解决Error:All flavors must now belong to a named flavor dimension. Learn more at...

    低版本的gradle里面不会出现这个错误,高版本出现,不多说,看如何解决 在defaultConfig{}中添加:flavorDimensions "default" 保证所有的f ...

  5. 安装windows 10到固态硬盘实践记录

    1.前提 由于之前一直用的机械硬盘,电脑用了几年是越来越慢,所以打算买个SSD,装个新系统,其他的机械硬盘都当从盘用 2.准备工作 SSD :256G 3星的 WIN10正版光盘一张 外置光驱一个 3 ...

  6. pyquery 学习

    pyquery 是python仿照jQuery的严格实现,语法与jQuery几乎完全相同,所以对于学过前端的朋友们可以立马上手,没学过的小朋友也别灰心,我们马上就能了解到pyquery的强大. 1 安 ...

  7. 在linux中访问macos 下的分区。

    花钱的解决方案是找专业的:   Paragon Software  他们家有各种套件,让你在window Linux 都能访问到苹果分区里面的内容. 但是Windows删除了它的驱动之后一开机就蓝屏. ...

  8. WEB框架-Django框架学习-关联管理器(RelatedManager)

    一.class RelatedManager "关联管理器"是在一对多或者多对多的关联上下文中使用的管理器.它存在于下面两种情况: 1.一对多 ForeignKey关系的“另一边” ...

  9. 普通程序员如何转向AI方向(转)

    普通程序员如何转向AI方向   眼下,人工智能已经成为越来越火的一个方向.普通程序员,如何转向人工智能方向,是知乎上的一个问题.本文是我对此问题的一个回答的归档版.相比原回答有所内容增加. 一. 目的 ...

  10. Markdown 插入图片技巧

    在使用Markdown编写博客或文件的时候,经常会需要插入图片.如果使用Markdown语法,我们会发现调整图片的大小会是个问题. 所以推荐使用另一种办法插入图片,使用HTML语法,示例如下: < ...