SpringBoot2.0整合多数据源拆分
前言
本文环境承接springboot2.0整合使用mybatis(数据访问篇)
一、什么是多数据源
公司分为两个数据库,一个数据库专门存放共同配置文件,一个数据库垂直业务数据库。垂直根据业务划分具体数据库。在一个项目中有多个数据源(连接不同库jdbc):无限大,具体多少根据内存大小。在一个项目多数据源如何划分:分包名(业务)|| 注解方式。
com.zhongguancun.test01— datasource1
com.zhongguancun.test02— datasource2
类似 多个不同jar, 不同业务需求。多个不同的业务需求,存放同一个项目中。
二、创建文件名称及位置
三、文件内容
1.MybatisApp02
package com.zhongguancun;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan(basePackages = { "com.zhongguancun.test01.mapper" , "com.zhongguancun.test02.mapper"})
public class MybatisApp02 {public static void main(String[] args) {SpringApplication.run(MybatisApp02.class, args);}}
2.MybatisMultilDataSourceController
package com.zhongguancun.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.zhongguancun.test01.service.UserServiceTest01;
import com.zhongguancun.test02.service.UserServiceTest02;/*** 多数据源测试* @author 86187**/
@RestController
public class MybatisMultilDataSourceController {@Autowiredprivate UserServiceTest01 userServiceTest01;@Autowiredprivate UserServiceTest02 userServiceTest02;@RequestMapping("/insertUserTest1")public Integer insertUserTest1(String name, Integer age) {return userServiceTest01.insertUser(name, age);}@RequestMapping("/insertUserTest2")public Integer insertUserTest2(String name, Integer age) {return userServiceTest02.insertUser(name, age);}
}
3.DataSource1Config
package com.zhongguancun.datasource;
import javax.sql.DataSource;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.jdbc.datasource.DataSourceTransactionManager;//DataSource01
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.zhongguancun.test01.mapper", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {/*** * @methodDesc: 功能描述:(配置test2数据库)* @author: 阿坤* @param: @return* @createTime:2020年10月15日 下午3:16:44* @returnType:@return DataSource* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test1DataSource")@ConfigurationProperties(prefix = "spring.datasource.test1")//@Primarypublic DataSource testDataSource() {return DataSourceBuilder.create().build();}/*** * @methodDesc: 功能描述:(test2 sql会话工厂)* @author: 阿坤* @param: @param* dataSource* @param: @return* @param: @throws* Exception* @createTime:2020年10月15日 下午3:17:08* @returnType:@param dataSource* @returnType:@return* @returnType:@throws Exception SqlSessionFactory* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test1SqlSessionFactory")//@Primarypublic SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);// bean.setMapperLocations(// new// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));return bean.getObject();}/*** * @methodDesc: 功能描述:(test2 事物管理)* @author: 阿坤* @param: @param* dataSource* @param: @return* @param: @throws* Exception* @createTime:2020年10月15日 下午3:17:08* @returnType:@param dataSource* @returnType:@return* @returnType:@throws Exception SqlSessionFactory* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test1TransactionManager")//@Primarypublic DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "test1SqlSessionTemplate")//@Primarypublic SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}
4.DataSource2Config
package com.zhongguancun.datasource;
import javax.sql.DataSource;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.jdbc.datasource.DataSourceTransactionManager;//DataSource02
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.zhongguancun.test02", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {/*** * @methodDesc: 功能描述:(配置test2数据库)* @author: 阿坤* @param: @return* @createTime:2020年10月15日 下午3:16:44* @returnType:@return DataSource* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test2DataSource")@ConfigurationProperties(prefix = "spring.datasource.test2")//@Primarypublic DataSource testDataSource() {return DataSourceBuilder.create().build();}/*** * @methodDesc: 功能描述:(test2 sql会话工厂)* @author: 阿坤* @param: @param* dataSource* @param: @return* @param: @throws* Exception* @createTime:2020年10月15日 下午3:17:08* @returnType:@param dataSource* @returnType:@return* @returnType:@throws Exception SqlSessionFactory* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test2SqlSessionFactory")//@Primarypublic SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);// bean.setMapperLocations(// new// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));return bean.getObject();}/*** * @methodDesc: 功能描述:(test2 事物管理)* @author: 阿坤* @param: @param* dataSource* @param: @return* @param: @throws* Exception* @createTime:2020年10月15日 下午3:17:08* @returnType:@param dataSource* @returnType:@return* @returnType:@throws Exception SqlSessionFactory* @copyright:北京阿坤教育* @QQ:974852727*/@Bean(name = "test2TransactionManager")//@Primarypublic DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "test2SqlSessionTemplate")//@Primarypublic SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}
5.User
package com.zhongguancun.entity;import lombok.Data;/*** 实体类层* @author 86187**/
@Data
public class User {private Integer id;private Integer age;private String name;public static void main(String[] args) {}}
6.UserMapperTest01
package com.zhongguancun.test01.mapper;import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;import com.zhongguancun.entity.User;public interface UserMapperTest01 {// 查询语句@Select("SELECT * FROM users WHERE NAME = #{name}")User findByName(@Param("name") String name);// 插入语句@Insert("INSERT INTO users(NAME, AGE) VALUES(#{name}, #{age})")int insert(@Param("name") String name, @Param("age") Integer age);
}
7.UserServiceTest01
package com.zhongguancun.test01.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.zhongguancun.test01.mapper.UserMapperTest01;import lombok.extern.slf4j.Slf4j;@Service
@Slf4j
public class UserServiceTest01 {@Autowiredprivate UserMapperTest01 userMapperTest01;// springboot1.5版本需要开启@Transactional注解,2.0版本已修复多数据源冲突问题无需注解//@Transactional(transactionManager = "test1TransactionManager")public int insertUser(String name, Integer age) {int insertUserResult = userMapperTest01.insert(name, age);//int i = 1 / age;log.info("###########insertUserResult:{}#########", insertUserResult);// 怎么样验证事务开启成功!~return insertUserResult;}
}
8.UserMapperTest02
package com.zhongguancun.test02.mapper;import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;import com.zhongguancun.entity.User;public interface UserMapperTest02 {// 查询语句@Select("SELECT * FROM users WHERE NAME = #{name}")User findByName(@Param("name") String name);// 插入语句@Insert("INSERT INTO users(NAME, AGE) VALUES(#{name}, #{age})")int insert(@Param("name") String name, @Param("age") Integer age);
}
9.UserServiceTest02
package com.zhongguancun.test02.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.zhongguancun.test02.mapper.UserMapperTest02;import lombok.extern.slf4j.Slf4j;@Service
@Slf4j
public class UserServiceTest02 {@Autowiredprivate UserMapperTest02 userMapperTest02;// springboot1.5版本需要开启@Transactional注解,2.0版本已修复多数据源冲突问题无需注解//@Transactional(transactionManager = "test2TransactionManager")public int insertUser(String name, Integer age) {int insertUserResult = userMapperTest02.insert(name, age);//int i = 1 / age;log.info("###########insertUserResult:{}#########", insertUserResult);// 怎么样验证事务开启成功!~return insertUserResult;}
}
10.application.properties
####datasource1
spring.datasource.test1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url=jdbc:mysql://192.168.200.222:3306/test01?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test1.username=root
spring.datasource.test1.password=123456####datasource2
spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url=jdbc:mysql://192.168.200.222:3306/test02?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test2.username=root
spring.datasource.test2.password=123456
11.pom.xml
<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><groupId>com.zhongguancun</groupId><artifactId>zhongguancun_springboot_mybatis</artifactId><version>0.0.1-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.0.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- 测试 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- mysql 依赖 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- springboot-web组件 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.20</version><!--$NO-MVN-MAN-VER$--><scope>provided</scope></dependency></dependencies>
</project>
四、效果演示
点击java Application
启动成功
打开浏览器分别输入:
http://localhost:8080/insertUserTest1?name=阿坤多源数据测试库001&age=001
http://localhost:8080/insertUserTest2?name=阿坤多源数据测试库002&age=002
返回数字一表示成功入库
后台显示成功调用截图如下
最后通过Navicat查看是否真正插入语句:
恭喜完成实验!
SpringBoot2.0整合多数据源拆分相关推荐
- SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题
SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题 参考文章: (1)SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题 (2)https://www. ...
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- SpringBoot2.0 整合 Redis集群 ,实现消息队列场景
本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/middle-ware-parent 一.Redis集群简介 1.RedisCluster概念 Re ...
- SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...
- SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...
- SpringBoot2.0整合SpringCache和Redis(lettuce)攻略
Redis Redis 是一个高性能的key-value数据库,广泛应用于互联网业务的缓存,如token池,商品缓存等等热点数据的缓存. linux原版官方地址 http://redis.io win ...
- SpringCloud、SpringBoot2.0 整合Oauth2 (四) 配置文件快速配置url过滤
SpringBoot2.0 整合Oauth2 (四) 配置文件快速配置url过滤 文章目录 SpringBoot2.0 整合Oauth2 (四) 配置文件快速配置url过滤 1.添加url过滤配置 2 ...
- SpringBoot2.0整合Redis实战
SpringBoot2.x整合Redis实战 1.分布式缓存Redis介绍 简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/down ...
- SpringBoot2.0 jpa多数据源配置
随着Springboot升级到2.0,原来1.5.x的Jpa多数据源配置不能用了.现在总结一下Springboot2.0的jpa多数据源配置 连接池还是用druid,但是不能用druid的starte ...
最新文章
- Suricata的输出
- 首位猪心移植患者去世!术后存活2个月,创造医学里程碑;官方讣告:哀悼并感谢所作巨大贡献...
- XP+UBUNTU双系统上重装XP后修复GRUB方法
- P4126 [AHOI2009]最小割(网络流/最小割)
- 在linux中dns不安装coching,ubuntu 8.04下openldap的安装和使用
- 11g下如何查询trace文件名
- 计算机专业很难找工作了???
- 集成ahci驱动的xp系统_IDE转AHCI模式 for win7+SSD
- 开务正式加入中国信通院数据库应用创新实验室
- 图片、图标等网址推荐
- java 三大特性_java的三大特性是什么?
- 如何设计一个应用软件
- 耀月家族公会部门规定职责等2011-11-26
- 教程┊解决使用USB键盘进行游戏后按任意键出现蓝屏的错误
- Java获取指定年月的开始时间和结束时间
- idea的tools下面没有deployment选项
- python 16.1 继承 重写 supper()方法 多重继承
- mysql中的case when 与if else
- 《第1阶段》——正交试验法
- 在线旅游市场的延进以及发展趋势访谈回顾
热门文章
- 德州学院计算机系吧,任传成(计算机系)老师 - 德州学院 - 院校大全
- 练手练到阅文集团作家中心了,python crawlspider 二维抓取学习
- 官方也无力回天?“SharedPreferences 存在什么问题?”
- vue:实现前端生成并下载二维码(使用qrcodejs2插件)
- 从零构建区块链量化交易平台课程总结-思维模型和方法论提炼
- MFC 入门级基础知识
- mfc editctrl限制输入
- 如何将pdf转换成ppt,pdf转ppt方法
- c语言实验指导修改版,高级语言程序设计(C语言)实验指导书(修改版).doc
- 深度挖掘:FIashGet下载隐藏链接[转]