springboot mybatis优雅的添加多数据源
springboot的原则是简化配置,本文试图不通过xml配置,使用configuration配置数据源,并进行简单的数据访问。
并且配置了多数据源,在开发过程中这种场景很容易遇到。
1、依赖
springboot的starter
mybatis的springboot集成包
jdbc
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
2、在application中打开configuration
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3、写主数据源的configuration
1)多数据源中有一个是主数据源,注意@primary注解的书写位置
2)MapperScan basePackages配置了扫描主数据源mapper的路径
3)//bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/sentinel/*.xml"));
注释掉了通过xml配置扩展sql的方式。如果频繁使用多表连接查询,可以打开自定义sql
package com.dqa.sentinel.configuration; 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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration
@MapperScan(basePackages = "com.dqa.sentinel.mapper.sentinel", sqlSessionTemplateRef = "sentinelSqlSessionTemplate")
public class SentinelDataSource { @Bean(name = "sentinelData")
@ConfigurationProperties(prefix = "spring.datasource.sentinel") // application.properteis中对应属性的前缀
@Primary
public DataSource sentinelData() {
return DataSourceBuilder.create().build();
} @Bean(name = "sentinelSqlSessionFactory")
@Primary
public SqlSessionFactory sentinelSqlSessionFactory(@Qualifier("sentinelData") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/sentinel/*.xml"));
return bean.getObject();
} @Bean(name = "sentinelTransactionManager")
@Primary
public DataSourceTransactionManager sentinelTransactionManager(@Qualifier("sentinelData") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "sentinelSqlSessionTemplate")
@Primary
public SqlSessionTemplate sentinelSqlSessionTemplate(@Qualifier("sentinelSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }
4、比如你还有一个外部数据源,再写一个configuration
tips:这里不能有@primary注解,不然会有冲突
package com.dqa.sentinel.configuration; 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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.dqa.sentinel.mapper.outer", sqlSessionTemplateRef = "outerSqlSessionTemplate")
public class OuterDataSource { @Bean(name = "outerData")
@ConfigurationProperties(prefix = "spring.datasource.outer") // application.properteis中对应属性的前缀
public DataSource outData() {
return DataSourceBuilder.create().build();
} @Bean(name = "outerSqlSessionFactory")
public SqlSessionFactory outerSqlSessionFactory(@Qualifier("outerData") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/outer/*.xml"));
return bean.getObject();
} @Bean(name = "outerTransactionManager")
public DataSourceTransactionManager outerTransactionManager(@Qualifier("outerData") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "outerSqlSessionTemplate")
public SqlSessionTemplate outerSqlSessionTemplate(@Qualifier("outerSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }
5、在mapper包中定义你需要的sql
路径要和刚才在configuration中配置的一样
package com.dqa.sentinel.mapper.sentinel; import com.dqa.sentinel.model.SentinelClan;
import org.apache.ibatis.annotations.*; import java.util.List; @Mapper
public interface SentinelMapper {
@Select("SELECT * FROM sentinelClan;")
List<SentinelClan> getAllClan(); @Select("SELECT * FROM sentinelClan WHERE id = #{id}")
SentinelClan getOneClan(@Param("id") Integer id); @Insert("INSERT INTO sentinelClan (id,clanName,topicNames,bufferTime,countWidth,countPercent,alarmGroup,status,createTime,updateTime) " +
"VALUES( #{id}, #{clanName}, #{topicNames}, #{bufferTime}, #{countWidth}, #{countPercent}, #{alarmGroup}, #{status}, #{createTime}, #{updateTime})")
int insertOne(SentinelClan sentinelClan); @Update("UPDATE sentinelClan SET clanName = #{clanName},topicNames = #{topicNames},bufferTime = #{bufferTime}," +
"countWidth = #{countWidth},countPercent = #{countPercent},alarmGroup = #{alarmGroup},status = #{status}," +
"createTime=#{createTime}, updateTime=#{updateTime}" +
"WHERE id = #{id}")
int updateOne(SentinelClan sentinelClan);
}
6、model中是实体类
个人爱好写的班班程程的,或者你可以在数据库建表之后使用generator自动生成。
package com.dqa.sentinel.model; import java.sql.Blob;
import java.util.Date; public class SentinelClan {
private Integer id ;
private String clanName;
private String topicNames;
private Integer bufferTime;
private Integer countWidth;
private Integer countPercent;
private String alarmGroup;
private Integer status;
private String createTime;
private String updateTime; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getClanName() {
return clanName;
}
public void setClanName(String clanName) {
this.clanName = clanName;
}
public String getTopicNames() {
return topicNames;
}
public void setTopicNames(String topicNames) {
this.topicNames = topicNames;
}
public Integer getBufferTime() {
return bufferTime;
}
public void setBufferTime(Integer bufferTime) {
this.bufferTime = bufferTime;
}
public Integer getCountWidth() {
return countWidth;
}
public void setCountWidth(Integer countWidth) {
this.countWidth = countWidth;
}
public Integer getCountPercent() {
return countPercent;
}
public void setCountPercent(Integer countPercent) {
this.countPercent = countPercent;
}
public String getAlarmGroup() {
return alarmGroup;
}
public void setAlarmGroup(String alarmGroup) {
this.alarmGroup = alarmGroup;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
}
springboot mybatis优雅的添加多数据源的更多相关文章
- SpringBoot Mybatis项目中的多数据源支持
1.概述 有时项目里里需要抽取不同系统中的数据源,需要访问不同的数据库,本文介绍在Springboot+Mybatis项目中如何支持多数据源操作. 有需要的同学可以下载 示例代码 项目结构如下: 2. ...
- SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
前言 本篇文章主要讲述的是SpringBoot整合Mybatis.Druid和PageHelper 并实现多数据源和分页.其中SpringBoot整合Mybatis这块,在之前的的一篇文章中已经讲述了 ...
- springboot+mybatis +yml文件配置多数据源
记录一下java开发中多数据源的配置过程, 参考博客:https://blog.csdn.net/weinichendian/article/details/72903757,我在这里进行了整理,使用 ...
- Springboot+Mybatis AOP注解动态切换数据源
在开发中因需求在项目中需要实现多数据源(虽然项目框架是SpringCloud,但是因其中只是单独的查询操作,觉得没必要开发一个项目,所以采用多数据源来进行实现) 1.在配置文件中创建多个数据连接配置 ...
- springboot添加多数据源连接池并配置Mybatis
springboot添加多数据源连接池并配置Mybatis 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/9190226.html May 12, 2018 ...
- springboot + mybatis + 多数据源
此文已由作者赵计刚薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验 在实际开发中,我们一个项目可能会用到多个数据库,通常一个数据库对应一个数据源. 代码结构: 简要原理: 1) ...
- DB数据源之SpringBoot+MyBatis踏坑过程(二)手工配置数据源与加载Mapper.xml扫描
DB数据源之SpringBoot+MyBatis踏坑过程(二)手工配置数据源与加载Mapper.xml扫描 liuyuhang原创,未经允许进制转载 吐槽之后应该有所改了,该方式可以作为一种过渡方式 ...
- DB数据源之SpringBoot+MyBatis踏坑过程(三)手工+半自动注解配置数据源与加载Mapper.xml扫描
DB数据源之SpringBoot+MyBatis踏坑过程(三)手工+半自动注解配置数据源与加载Mapper.xml扫描 liuyuhang原创,未经允许禁止转载 系列目录连接 DB数据源之Spr ...
- DB数据源之SpringBoot+MyBatis踏坑过程(五)手动使用Hikari连接池
DB数据源之SpringBoot+MyBatis踏坑过程(五)手动使用Hikari连接池 liuyuhang原创,未经允许禁止转载 系列目录连接 DB数据源之SpringBoot+Mybatis踏坑 ...
随机推荐
- Beta冲刺前准备
一.介绍小组新成员,Ta担任的角色. 201421123121 栗海辉 来自Sugar Free 风格:低调中的高调,给你不一样的视觉 擅长的技术:C语言/JAVA 在曾经的团队里面担任主要编程人员, ...
- 201521123008《Java程序设计》第八周实验总结
1. 本周学习总结 2. 书面作业 本次作业题集集合 1.List中指定元素的删除(题目4-1) 1.1 实验总结 1.删除元素的时候从最后一个元素开始,避免删除元素后位置发生变化而导致有些元素没有删 ...
- 201521123075 《Java程序设计》第1周学习总结
1. 本周学习总结 (1)Java不仅是程序语言,还是一种标准规范,代表着解决问题的方案.Java是一个面向对象的编程语言,熟悉后相对于c++更方便,其一大特色就是能够跨平台运行. (2)Java发展 ...
- 让你的python程序同时兼容python2和python3
python邮件列表里有人发表言论说「python3在10内都无法普及」.在我看来这样的观点有些过于悲观,python3和python2虽然不兼容,但他们之间差别并没很多人想像的那么大.你只需要对自己 ...
- 12个Sublime Text应用技巧和诀窍
本文为您提供Sublime Text编辑器的12个技巧和诀窍,深入挖掘这个看似简洁的代码编辑器,背后所隐藏的实现各种高级功能的无限可能. 1) 选择 以下是一些Sublime Text选择文本的快捷键 ...
- 201521123098 JAVA课程设计
1.团队课程设计博客链接 http://www.cnblogs.com/agts/p/7067948.html 2.个人负责模块或任务说明 个人任务:实现初始界面中的登录.注册模块,以及数据库的连接和 ...
- 克隆虚拟机 virtualbox 修改 uuid
cmd E:\Program Files\Oracle\VirtualBox>VBoxManage.exe internalcommands sethduuid "E:\Program ...
- 全方位解读"CPU load average"
前一段时间,有同事因为“CPU负载到达5算不算高”的问题争论了一番,看似简单的一个问题表明了我们并没有真正理解服务器的CPU负载. 如果你的线上服务出现性能问题,那么检查机器的CPU负载情况是必不可少 ...
- 只用一招让你Maven依赖下载速度快如闪电
一.背景 众所周知,Maven对于依赖的管理让我们程序员感觉爽的不要不要的,但是由于这货是国外出的,所以在我们从中央仓库下载依赖的时候,速度如蜗牛一般,让人不能忍,并且这也是大多数程序员都会遇到的问题 ...
- multimap 和priority_queue详解
上一期是关于STL和并查集结合的例题,也附了STL中部分容器的使用摘要,由于是从网上东拼西凑的,感觉有的关键点还是没解释清楚,现在从其中摘出两个容器,用例题对它们的用法进行进一步解释. 以下是例题的介 ...