springboot中配置多数据源mybatisPlus
文章目录
- 1 背景
- 2 版本
- 3 配置
- 3.1 pom配置
- 3.1.1 父类pom
- 3.1.2 pom依赖
- 3.1.3 插件
- 3.2 application.yml配置
- 3.3 启动类配置
- 4 使用
- 4.1 建表脚本
- 4.2 实体类
- 4.3 mapper
- 4.4 mapper映射
- 4.5 使用
1 背景
springboot配置mybatisPlus
,mybatisPlus配置一主二从
数据源。
数据源根据在切面方法
上配置@DS
注解选择对应的数据源,默认
数据源为master
。配置@DS("slave")
注解,随机
从slave_1和slave_1中选择从库数据源。
2 版本
- JDK:
1.8
- mysql:
5.6
- springboot:
2.2.9.RELEASE
- mybatis-plus:
3.2.0
3 配置
路径说明:
用途 | 路径 |
---|---|
bean | com.sa.example.mybatis.ext.bean |
mapper | com.sa.example.mybatis.ext.mapper;com.sa.example.mybatis.auto.mapper |
xml | com.sa.example.mybatis.ext.mapper.xml;com.sa.example.mybatis.auto.mapper.xml |
3.1 pom配置
3.1.1 父类pom
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.9.RELEASE</version><relativePath/>
</parent>
3.1.2 pom依赖
<!-- ==========mybatisPlus依赖========== -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.30</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.23</version>
</dependency>
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version>
</dependency>
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.2.0</version>
</dependency>
<!-- ==========springboot-web依赖========== -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- ==========其他依赖========== -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope>
</dependency>
3.1.3 插件
保证可以在src
的包里配置mapper的xml文件,否则需要再resource
文件夹中配置mapper的xml。
<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>**/*.*</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/**</include></includes></resource></resources>
</build>
3.2 application.yml配置
spring:# ==========mybatis-plus数据源配置==========datasource:dynamic:primary: master #设置默认的数据源或者数据源组,默认值即为masterstrict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.datasource:master:url: jdbc:mysql://127.0.0.1:3306/test01?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round&useAffectedRows=trueusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driverdruid:initialSize: 100minIdle: 50maxActive: 200maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: falsemaxPoolPreparedStatementPerConnectionSize: -1filters: statslave_1:url: jdbc:mysql://127.0.0.1:3306/test02?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round&useAffectedRows=trueusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driverdruid:initialSize: 100minIdle: 50maxActive: 200maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: falsemaxPoolPreparedStatementPerConnectionSize: -1filters: statslave_2:url: jdbc:mysql://127.0.0.1:3306/test03?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round&useAffectedRows=trueusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driverdruid:initialSize: 100minIdle: 50maxActive: 200maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: falsemaxPoolPreparedStatementPerConnectionSize: -1filters: stat#==========整合mybatisPlus==========
mybatis-plus:type-aliases-package: com.lx.ms.db.mybatis.bean.ext# 配置mybatis的xml路径mapper-locations: classpath:com/sa/example/mybatis/ext/mapper/xml/*.xml,classpath:com/sa/example/mybatis/auto/mapper/xml/*.xmlconfiguration:map-underscore-to-camel-case: truecache-enabled: truelazy-loading-enabled: falseaggressive-lazy-loading: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.3 启动类配置
@SpringBootApplication(scanBasePackages = "com.sa.example")
// 配置xml的mapper路径
@MapperScan(basePackages = {"com.sa.example.mybatis.ext.mapper", "com.sa.example.mybatis.auto.mapper"})
public class MybatisApplication {public static void main(String[] args) {SpringApplication.run(MybatisApplication.class, args);}
}
4 使用
4.1 建表脚本
CREATE TABLE `c_m_phone` (`id` int(10) NOT NULL COMMENT 'id',`phone_first` varchar(20) DEFAULT NULL COMMENT '前缀号段',`phone_provence` varchar(20) DEFAULT NULL COMMENT '手机所在省份',`phone_city` varchar(20) DEFAULT NULL COMMENT '手机所在城市',`service` varchar(20) DEFAULT NULL COMMENT '服务商',PRIMARY KEY (`id`)
) COMMENT='电话区域表';
4.2 实体类
//包名:com.sa.example.mybatis.ext.bean
@Data
public class CMPhone {private Integer id;private String phoneFirst;private String phoneProvence;private String phoneCity;private String service;
}
4.3 mapper
// 包名:com.sa.example.mybatis.ext.mapper
public interface CMPhoneMapper {/*** 保存(配置主库)* @param model* @return*/@DS("master")int save(CMPhone model);/*** 查询(配置从库)* @param model* @return*/@DS("slave")List<CMPhone> findList(CMPhone model);
}
4.4 mapper映射
<!-- 包名:com.sa.example.mybatis.ext.mapper.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sa.example.mybatis.ext.mapper.CMPhoneMapper"><resultMap id="BaseResultMap" type="com.sa.example.mybatis.ext.bean.CMPhone"><id column="id" property="id" jdbcType="INTEGER"/><result column="phone_first" property="phoneFirst" jdbcType="VARCHAR"/><result column="phone_provence" property="phoneProvence" jdbcType="VARCHAR"/><result column="phone_city" property="phoneCity" jdbcType="VARCHAR"/><result column="service" property="service" jdbcType="VARCHAR"/></resultMap><select id="findList" parameterType="com.sa.example.mybatis.ext.bean.CMPhone" resultMap="BaseResultMap">select id,phone_first,phone_provence,phone_city,service from c_m_phone</select><insert id="save" parameterType="com.sa.example.mybatis.ext.bean.CMPhone">INSERT INTO `c_m_phone` (`id`, `phone_first`, `phone_provence`, `phone_city`, `service`) VALUES (#{id},#{phoneFirst},#{phoneProvence},#{phoneCity},#{service})</insert>
</mapper>
4.5 使用
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MybatisApplication.class)
public class MybatisTest {@Autowiredprivate CMPhoneMapper cmPhoneMapper;@Testpublic void testMapper() {List<CMPhone> cmPhoneList = cmPhoneMapper.findList(new CMPhone());System.out.println(cmPhoneList);}@Testpublic void testSave(){CMPhone model = new CMPhone();model.setId(1000);model.setPhoneCity("PhoneCity test");model.setPhoneFirst("PhoneFirst test");model.setPhoneProvence("PhoneProvence test");model.setService("Service test");cmPhoneMapper.save(model);}
}
springboot中配置多数据源mybatisPlus相关推荐
- springboot中配置mybatis数据源,使用阿里的 Druid 数据库连接池
参考了很多文章,记录下自己的学习过程! 参考:https://blog.csdn.net/weixin_40776321/article/details/99633110 1. 在pom.xml中添加 ...
- 关于SpringBoot中的多数据源集成
引言 其实对于分库分表这块的场景,目前市场上有很多成熟的开源中间件,eg:MyCAT,Cobar,sharding-JDBC等. 本文主要是介绍基于springboot的多数据源切换,轻量级的一种集成 ...
- db2 springboot 整合_[SpringBoot]快速配置多数据源(整合MyBatis)
前言 由于业务需求,需要同时在SpringBoot中配置两套数据源(连接两个数据库),要求能做到service层在调用各数据库表的mapper时能够自动切换数据源,也就是mapper自动访问正确的数据 ...
- springboot+jpa配置多数据源(Oracle+SqlServer)
本贴主要讲解配置多数据源 springboot+jpa的整合需要自行准备好 1.maven中要导入Oracle和SqlServer的jar包 <dependency><groupId ...
- springboot jpa 配置多数据源
jpa 多数据源配置 多个 mysql 数据库配置 springboot jpa 配置多数据源其实也并不难,只需要在 properties 或者 yml中简单配置并在项目中引入配置即可. 下面以 ym ...
- SpringBoot JPA配置多数据源(同类型库)教程
SpringBoot项目配置多数据源主要分为以下个步骤: 确定好所连接的数据库的资源(包括url username password) 将两个库的信息写入到配置文件中(application.yaml ...
- Spring中配置DataSource数据源的几种选择
Spring中配置DataSource数据源的几种选择 在Spring框架中有如下3种获得DataSource对象的方法: 从JNDI获得DataSource. 从第三方的连接池获得DataSourc ...
- springboot中配置了拦截器后,拦截器无效的解决方案之一
springboot中配置了拦截器后,拦截器无效的解决方案之一 参考文章: (1)springboot中配置了拦截器后,拦截器无效的解决方案之一 (2)https://www.cnblogs.com/ ...
- SpringBoot中配置为开发模式,代码修改后不用重新运行
场景 SpringBoot中配置为开发模式,修改代码后不用重新运行. 实现 打开pom.xml,添加依赖 <!-- 添加如下依赖,配置为开发模式,代码做了修改,不用重新运行--><! ...
最新文章
- 程序员也想改 Lottie 动画?是的!
- Eclipse使用Maven时出现:Index downloads are disabled, search results may be incomplete.问题解决...
- xpath提取html属性,xpath提取 html标签的文字内容
- nuxt 服务器构建因太耗CPU进程被杀解决办法
- 前端学习(2735):重读vue电商网站45之项目优化上线
- oracle计算表的大小,简要分析估算oracle表的大小
- linux的trace文件路径,linux系统分析工具之Blktrace(十)
- 阶乘数码(洛谷P1591题题解,Java语言描述)
- javascript学习之利用方向键控制div模块的移动
- VC 2010下安装OpenCV2.4.4(来自wiki)
- 2019中兴捧月·初赛心得
- IDEA左侧目录,按照文件夹排序
- TX-LCN分布式事务
- 带宽与速度的换算(表达式+例子)
- 计算机开机总要按f1键,为什么开机要按f1键?win7每次开机按f1才能进入系统怎么办...
- 聊聊技术专家谈阿里云史诗级故障
- unity画线之模拟小球抛物线运动轨迹
- 使用NDWI提取水体详细流程
- 武汉新时标文化传媒有限公司“土味”正在崛起,短视频的春天来了
- ORB+GMS、FREAK+GMS、BRISK+GMS、AKAZE+GMS特征点结合使用方法
热门文章
- [u]intN_t - uint8_t, uint16_t, uint32_t, uint64_t
- java常用api简单统计
- sklearn搭建线性模型的总结
- Java中循环删除list中元素的方法总结(总结)
- filewriter判断是否关闭_IO流详解
- python找色_[REST API] 用Python实现颜色识别功能----Total Control区域找色
- linux 挂载u盘考试,Linux 挂载U盘,与解挂
- linux下查看usb插拔日志,Linux:如何检测usb键盘是否已插入和拔出
- linux用于开发qt java_Linux下Qt程序的打包发布
- dd var tmp .oracle,Oracle 11gR2 RAC ohasd failed to start 解决方法