SpringBoot2 配置多数据源,整合MybatisPlus增强插件
本文源码:GitHub·点这里 || GitEE·点这里
一、项目案例简介
1、多数据简介
实际的项目中,经常会用到不同的数据库以满足项目的实际需求。随着业务的并发量的不断增加,一个项目使用多个数据库:主从复制、读写分离、分布式数据库等方式,越来越常见。
2、MybatisPlus简介
MyBatis-Plus(简称 MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。
插件特点
无代码侵入:只做增强不做改变,引入它不会对现有工程产生影响。
强大的 CRUD 操作:通过少量配置即可实现单表大部分 CRUD 操作满足各类使用需求。
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件。
支持主键自动生成:可自由配置,解决主键问题。
内置代码生成器:采用代码或者 Maven 插件可快速生成各层代码。
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作。
内置性能分析插件:可输出 Sql 语句以及其执行时间。
二、多数据源案例
1、项目结构
注意:mapper层和mapper.xml层分别放在不同目录下,以便mybatis扫描加载。
2、多数据源配置
spring:# 数据源配置datasource:type: com.alibaba.druid.pool.DruidDataSourceadmin-data:driverClassName: com.mysql.jdbc.DriverdbUrl: jdbc:mysql://127.0.0.1:3306/cloud-admin-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: rootpassword: 123initialSize: 20maxActive: 100minIdle: 20maxWait: 60000poolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 30timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 30000maxEvictableIdleTimeMillis: 60000validationQuery: SELECT 1 FROM DUALtestOnBorrow: falsetestOnReturn: falsetestWhileIdle: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000filters: stat,walluser-data:driverClassName: com.mysql.jdbc.DriverdbUrl: jdbc:mysql://127.0.0.1:3306/cloud-user-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: rootpassword: 123initialSize: 20maxActive: 100minIdle: 20maxWait: 60000poolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 30timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 30000maxEvictableIdleTimeMillis: 60000validationQuery: SELECT 1 FROM DUALtestOnBorrow: falsetestOnReturn: falsetestWhileIdle: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000filters: stat,wall
这里参数的形式是多样的,只需要配置参数扫描即可。
3、参数扫描类
@Component
@ConfigurationProperties(prefix = "spring.datasource.admin-data")
public class DruidOneParam {private String dbUrl;private String username;private String password;private String driverClassName;private int initialSize;private int maxActive;private int minIdle;private int maxWait;private boolean poolPreparedStatements;private int maxPoolPreparedStatementPerConnectionSize;private int timeBetweenEvictionRunsMillis;private int minEvictableIdleTimeMillis;private int maxEvictableIdleTimeMillis;private String validationQuery;private boolean testWhileIdle;private boolean testOnBorrow;private boolean testOnReturn;private String filters;private String connectionProperties;// 省略 GET 和 SET
}
4、配置Druid连接池
@Configuration
@MapperScan(basePackages = {"com.data.source.mapper.one"},sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class DruidOneConfig {private static final Logger LOGGER = LoggerFactory.getLogger(DruidOneConfig.class) ;@Resourceprivate DruidOneParam druidOneParam ;@Bean("dataSourceOne")public DataSource dataSourceOne () {DruidDataSource datasource = new DruidDataSource();datasource.setUrl(druidOneParam.getDbUrl());datasource.setUsername(druidOneParam.getUsername());datasource.setPassword(druidOneParam.getPassword());datasource.setDriverClassName(druidOneParam.getDriverClassName());datasource.setInitialSize(druidOneParam.getInitialSize());datasource.setMinIdle(druidOneParam.getMinIdle());datasource.setMaxActive(druidOneParam.getMaxActive());datasource.setMaxWait(druidOneParam.getMaxWait());datasource.setTimeBetweenEvictionRunsMillis(druidOneParam.getTimeBetweenEvictionRunsMillis());datasource.setMinEvictableIdleTimeMillis(druidOneParam.getMinEvictableIdleTimeMillis());datasource.setMaxEvictableIdleTimeMillis(druidOneParam.getMaxEvictableIdleTimeMillis());datasource.setValidationQuery(druidOneParam.getValidationQuery());datasource.setTestWhileIdle(druidOneParam.isTestWhileIdle());datasource.setTestOnBorrow(druidOneParam.isTestOnBorrow());datasource.setTestOnReturn(druidOneParam.isTestOnReturn());datasource.setPoolPreparedStatements(druidOneParam.isPoolPreparedStatements());datasource.setMaxPoolPreparedStatementPerConnectionSize(druidOneParam.getMaxPoolPreparedStatementPerConnectionSize());try {datasource.setFilters(druidOneParam.getFilters());} catch (Exception e) {LOGGER.error("druid configuration initialization filter", e);}datasource.setConnectionProperties(druidOneParam.getConnectionProperties());return datasource;}@Beanpublic SqlSessionFactory sqlSessionFactoryOne() throws Exception{SqlSessionFactoryBean factory = new SqlSessionFactoryBean();ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();factory.setDataSource(dataSourceOne());factory.setMapperLocations(resolver.getResources("classpath*:/dataOneMapper/*.xml"));return factory.getObject();}@Bean(name="transactionManagerOne")public DataSourceTransactionManager transactionManagerOne(){return new DataSourceTransactionManager(dataSourceOne());}@Bean(name = "sqlSessionTemplateOne")public SqlSessionTemplate sqlSessionTemplateOne() throws Exception {return new SqlSessionTemplate(sqlSessionFactoryOne());}
}
注意事项
- MapperScan 在指定数据源上配置;
- SqlSessionFactory 配置扫描的Mapper.xml地址 ;
- DataSourceTransactionManager 配置该数据源的事务;
- 两个数据源的配置手法相同,不赘述 ;
5、操作案例
- 数据源一:简单查询
@Service
public class AdminUserServiceImpl implements AdminUserService {@Resourceprivate AdminUserMapper adminUserMapper ;@Overridepublic AdminUser selectByPrimaryKey (Integer id) {return adminUserMapper.selectByPrimaryKey(id) ;}
}
- 数据源二:事务操作
@Service
public class UserBaseServiceImpl implements UserBaseService {@Resourceprivate UserBaseMapper userBaseMapper ;@Overridepublic UserBase selectByPrimaryKey(Integer id) {return userBaseMapper.selectByPrimaryKey(id);}// 使用指定数据源的事务@Transactional(value = "transactionManagerTwo")@Overridepublic void insert(UserBase record) {// 这里数据写入失败userBaseMapper.insert(record) ;// int i = 1/0 ;}
}
注意:这里的需要指定该数据源配置的事务管理器。
三、MybatisPlus案例
1、核心依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.7.1</version><exclusions><exclusion><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId></exclusion></exclusions>
</dependency>
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.0.7.1</version>
</dependency>
2、配置文件
mybatis-plus:mapper-locations: classpath*:/mapper/*.xmltypeAliasesPackage: com.digital.market.*.entityglobal-config:db-config:id-type: AUTOfield-strategy: NOT_NULLlogic-delete-value: -1logic-not-delete-value: 0banner: falseconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplmap-underscore-to-camel-case: truecache-enabled: falsecall-setters-on-nulls: truejdbc-type-for-null: 'null'
3、分层配置
mapper层
UserBaseMapper extends BaseMapper<UserBase>
实现层
UserBaseServiceImpl extends ServiceImpl<UserBaseMapper,UserBase> implements UserBaseService
接口层
UserBaseService extends IService<UserBase>
4、mapper.xml文件
<mapper namespace="com.plus.batis.mapper.UserBaseMapper" ><resultMap id="BaseResultMap" type="com.plus.batis.entity.UserBase" ><id column="id" property="id" jdbcType="INTEGER" /><result column="user_name" property="userName" jdbcType="VARCHAR" /><result column="pass_word" property="passWord" jdbcType="VARCHAR" /><result column="phone" property="phone" jdbcType="VARCHAR" /><result column="email" property="email" jdbcType="VARCHAR" /><result column="create_time" property="createTime" jdbcType="TIMESTAMP" /><result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /><result column="state" property="state" jdbcType="INTEGER" /></resultMap><sql id="Base_Column_List" >id, user_name, pass_word, phone, email, create_time, update_time, state</sql><select id="selectByParam" parameterType="com.plus.batis.entity.QueryParam" resultMap="BaseResultMap">select * from hc_user_base</select>
</mapper>
注意事项
BaseMapper中的方法都已默认实现;这里也可以自定义实现一些自己的方法。
5、演示接口
@RestController
@RequestMapping("/user")
public class UserBaseController {private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseController.class) ;@Resourceprivate UserBaseService userBaseService ;@RequestMapping("/info")public UserBase getUserBase (){return userBaseService.getById(1) ;}@RequestMapping("/queryInfo")public String queryInfo (){UserBase userBase1 = userBaseService.getOne(new QueryWrapper<UserBase>().orderByDesc("create_time")) ;LOGGER.info("倒叙取值:{}",userBase1.getUserName());Integer count = userBaseService.count() ;LOGGER.info("查询总数:{}",count);UserBase userBase2 = new UserBase() ;userBase2.setId(1);userBase2.setUserName("spring");boolean resFlag = userBaseService.saveOrUpdate(userBase2) ;LOGGER.info("保存更新:{}",resFlag);Map<String, Object> listByMap = new HashMap<>() ;listByMap.put("state","0") ;Collection<UserBase> listMap = userBaseService.listByMap(listByMap) ;LOGGER.info("ListByMap查询:{}",listMap);boolean removeFlag = userBaseService.removeById(3) ;LOGGER.info("删除数据:{}",removeFlag);return "success" ;}@RequestMapping("/queryPage")public IPage<UserBase> queryPage (){QueryParam param = new QueryParam() ;param.setPage(1);param.setPageSize(10);param.setUserName("cicada");param.setState(0);return userBaseService.queryPage(param) ;}@RequestMapping("/pageHelper")public PageInfo<UserBase> pageHelper (){return userBaseService.pageHelper(new QueryParam()) ;}
}
这里pageHelper方法是使用PageHelper插件自定义的方法。
四、源代码地址
GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent
SpringBoot2 配置多数据源,整合MybatisPlus增强插件相关推荐
- mybatisplus代码生成连接池_SpringBoot2 高级案例(15): 配置多数据源,整合MybatisPlus增强插件...
一.项目案例简介 1.多数据简介 实际的项目中,经常会用到不同的数据库以满足项目的实际需求.随着业务的并发量的不断增加,一个项目使用多个数据库:主从复制.读写分离.分布式数据库等方式,越来越常见. 2 ...
- 【SpringBoot 2学习笔记】《十一》SpringBoot2配置多数据源访问数据库
官方说明:Spring Boot 2.X 版本不再支持配置继承,多数据源的话每个数据源的所有配置都需要单独配置,否则配置不会生效.所以需要单独配置多个数据源的配置项.这里需要注意的是多个数据源的配置区 ...
- SpringBoot配置多数据源Mybatis/MybatisPlus/mysql
一.前言 项目开发过程中,单一数据源不能满足开发需求或者需要用到主从数据库的时候,引入多数据源配置在项目中显得尤为必要.下面简单介绍一种在spingboot中结合mybatis针对同类型的数据源mys ...
- springboot2.0 多数据源整合问题 At least one JPA metamodel must be present! at
2019独角兽企业重金招聘Python工程师标准>>> 数据源代码: 第一个读取配置文件代码: package com.datasource;import org.apache.ib ...
- SpringBoot一站式功能提供框架(一)整合MybatisPlus、整合Swagger Knif4j、整合Druid多数据源--柚子真好吃
SpringBoot一站式功能提供框架(一)整合MybatisPlus.整合Swagger Knif4j.整合Druid多数据源--柚子真好吃 一.前言 二.功能描述 三.具体实现 四.开源地址 一. ...
- 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 使用 ...
- SpringBoot+SpringMVC+MybatisPlus框架整合实现分页插件查询
2019独角兽企业重金招聘Python工程师标准>>> 1.首先介绍一下,mybatisPlus 根据官方文档的介绍,MybatisPlus(简称mp)是对mybatis的增强而不做 ...
- 这才是SpirngBoot轻松整合MybatisPlus多数据源的正确打开方式
有一个这样子的需求,线上正在跑的业务,由于业务发展需要,需重新开发一套新系统,等新系统开发完成后,需要无缝对接切换,当初具体设计见草图. 添加依赖# <!--lombok--><de ...
- SpringBoot整合MybatisPlus多数据源
相信在很多使用MybatisPlus框架的小伙伴都会遇到多数据源的配置问题,并且官网也给出了推荐使用多数据源 (dynamic-datasource-spring-boot-starter) 组件来实 ...
最新文章
- hibernate关联关系(多对多)
- java包含点_Java的21个核心技术点,你知道吗
- Spring Security——认证失败时获取认证信息(用户名、密码、IP、SESSIONID)
- delphi7aes加密解密与java互转_Java 加密/解密Excel
- Redis 通过 RDB 方式进行数据备份与还原
- jquery插件合集之图片裁剪
- 虚拟服务器ftp上传权限设置,13. 为 FTP虚拟用户设置“不同文件目录”和“访问权限”...
- bug-Skipping optimization due to error while loading function libraries: Invalid argument: Functions
- 文字处理技术:WORD也在不断变化中
- Python面向对象练习-乌龟吃鱼
- 玩客云添加到我的计算机,玩客云怎么备份?将电脑文件备份到玩客云教程
- 程序员视角的计算机系统 第一章 计算机系统 之旅
- 使用html5制作表格
- 计算机应用最普遍的汉字字符编码是什么,什么是计算机中应用最普遍的字符编码...
- 智慧园区数据可视化解决方案
- 每日一书丨嵌入式C语言自我修养:从芯片、编译器到操作系统
- 操作系统原理_田丽华(11)大容量存储
- PowerDNS - Realtime Update 的 DNS 伺服器介紹
- 天才少女到美女CEO(图)
- 桌面美化--鼠标指针