手把手教你如何扩展(破解)mybatisplus的sql生成
mybatisplus 的常用CRUD方法
众所周知,mybatisplus提供了强大的代码生成能力,他默认生成的常用的CRUD方法(例如插入、更新、删除、查询等)的定义,能够帮助我们节省很多体力劳动。
他的BaseMapper中定义了这些常用的CRUD方法,我们在使用时,继承这个BaseMapper类就默认拥有了这些能力。

如果我们的业务中,需要类似的通用Sql时,该如何实现呢?
是每个Mapper中都定义一遍类似的Sql吗?
显然这是最笨的一种方法。
此时我们可以借助mybatisplus这个成熟框架,来实现我们想要的通用Sql。
扩展常用CRUD方法
新增一个通用sql
比如有一个这样的需求,项目中所有表或某一些表,都要执行一个类似的查询,如`SelectByErp`,那么可以这样实现。(这是一个最简单的sql实现,使用时可以根据业务需求实现更为复杂的sql:比如多租户系统自动增加租户id参数、分库分表系统增加分库分表字段条件判断)
定义一个
SelectByErp类,继承AbstractMethod类,并实现injectMappedStatement方法定义sql方法名、sql模板、实现sql的拼接组装
/**
* 新增一个通用sql
*/
public class SelectByErp extends AbstractMethod {
// 需要查询的列名
private final String erpColumn = "erp";
// sql方法名
private final String method = "selectByErp";
// sql模板
private final String sqlTemplate = "SELECT %s FROM %s WHERE %s=#{%s} %s";
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
// 获取需要查询的字段名及属性名
TableFieldInfo erpFiled = getErpProperty(tableInfo);
// 拼接组装sql
SqlSource sqlSource = new RawSqlSource(configuration, String.format(sqlTemplate,
sqlSelectColumns(tableInfo, false),
tableInfo.getTableName(),
erpFiled.getColumn(), erpFiled.getProperty(),
tableInfo.getLogicDeleteSql(true, false)), Object.class);
return this.addSelectMappedStatementForTable(mapperClass, method, sqlSource, tableInfo);
}
/**
* 查询erp列信息
*/
private TableFieldInfo getErpProperty(TableInfo tableInfo) {
List<TableFieldInfo> fieldList = tableInfo.getFieldList();
TableFieldInfo erpField = fieldList.stream().filter(filed -> filed.getColumn().equals(erpColumn)).findFirst().get();
return erpField;
}
3.定义一个sql注入器GyhSqlInjector,添加SelectByErp对象
// 需注入到spring容器中
@Component
public class GyhSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
// 增加 SelectByErp对象,程序启动后自动加载
methodList.add(new SelectByErp());
return methodList;
}
}
4.定义一个基础MapperGyhBaseMapper,添加selectByErp方法
/**
* 自定义的通用Mapper
*/
public interface GyhBaseMapper<T> extends BaseMapper<T> {
List<T> selectByErp(String erp);
}
5.应用中需要使用该SelectByErp方法的表,都继承GyhBaseMapper,那么这些表将都拥有了selectByErp这个查询方法,程序启动后会自动为这些表生成该sql。
public interface XXXMapper extends GyhBaseMapper<XXXTable>
添加一个mybatisplus已有sql
1.mybatisplus 常用CRUD方法如最上图,这些方法已经默认会自动生成,但mybatisplus其实提供了更多的方法,如下图,只要我们在启动时添加进去,就可以使用了。

2.比如我想使用AlwaysUpdateSomeColumnById方法,该方法可以在更新时只更新我需要的字段,不进行全字段更新。添加步骤如下。
3.定义一个sql注入器 ,如GyhSqlInjector,添加AlwaysUpdateSomeColumnById对象
@Component
public class GyhSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
// 添加 AlwaysUpdateSomeColumnById 对象
methodList.add(new AlwaysUpdateSomeColumnById());
return methodList;
}
}
4.定义一个基础Mapper 如GyhBaseMapper,添加alwaysUpdateSomeColumnById方法
/**
* 自定义的通用Mapper
*/
public interface GyhBaseMapper<T> extends BaseMapper<T> {
int alwaysUpdateSomeColumnById(@Param(Constants.ENTITY) T entity);
}
5.继承GyhBaseMapper的其他Mapper,将自动拥有alwaysUpdateSomeColumnById方法
/**
* 自定义的通用Mapper
*/
public interface GyhBaseMapper<T> extends BaseMapper<T> {
int alwaysUpdateSomeColumnById(@Param(Constants.ENTITY) T entity);
}
6.继承GyhBaseMapper的其他Mapper,将自动拥有alwaysUpdateSomeColumnById方法
编辑一个mybatisplus已有sql
1.如果想编辑一个mybatisplus已有sql,比如分库分表系统,执行updateById操作时,虽然主键Id已确定,但目标表不确定,此时可能导致该sql在多张表上执行,造成资源浪费,并且分库分表字段不可修改,默认的updateById不能用,需要改造。以下以shardingsphere分库分表为例。
2.定义一个UpdateByIdWithSharding类,继承UpdateById类
public class UpdateByIdWithSharding extends UpdateById {
private String columnDot = "`";
private YamlShardingRuleConfiguration yamlShardingRuleConfiguration;
// 注入shardingsphere的分库分表配置信息
public UpdateByIdWithSharding(YamlShardingRuleConfiguration yamlShardingRuleConfiguration) {
this.yamlShardingRuleConfiguration = yamlShardingRuleConfiguration;
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String tableName = tableInfo.getTableName();
// shardingsphere 分库分表配置信息
Map<String, YamlTableRuleConfiguration> tables = yamlShardingRuleConfiguration.getTables();
// 判断当前表是否设置了分表字段
if (tables.containsKey(tableName)) {
YamlTableRuleConfiguration tableRuleConfiguration = tables.get(tableName);
// 获取分表字段
String shardingColumn = tableRuleConfiguration.getTableStrategy().getStandard().getShardingColumn();
// 构建sql
boolean logicDelete = tableInfo.isLogicDelete();
SqlMethod sqlMethod = SqlMethod.UPDATE_BY_ID;
// 增加分表字段判断
String shardingAdditional = getShardingColumnWhere(tableInfo, shardingColumn);
// 是否判断逻辑删除字段
final String additional = optlockVersion() + tableInfo.getLogicDeleteSql(true, false);
shardingAdditional = shardingAdditional + additional;
String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
getSqlSet(logicDelete, tableInfo, shardingColumn),
tableInfo.getKeyColumn(), ENTITY_DOT + tableInfo.getKeyProperty(),
shardingAdditional);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
} else {
return super.injectMappedStatement(mapperClass, modelClass, tableInfo);
}
}
/**
* where条件增加分表字段
*/
private String getShardingColumnWhere(TableInfo tableInfo, String shardingColumn) {
StringBuilder shardingWhere = new StringBuilder();
shardingWhere.append(" AND ").append(shardingColumn).append("=#{");
shardingWhere.append(ENTITY_DOT);
TableFieldInfo fieldInfo = tableInfo.getFieldList().stream()
.filter(f -> f.getColumn().replaceAll(columnDot, StringUtils.EMPTY).equals(shardingColumn))
.findFirst().get();
shardingWhere.append(fieldInfo.getEl());
shardingWhere.append("}");
return shardingWhere.toString();
}
/**
* set模块去掉分表字段
*/
public String getSqlSet(boolean ignoreLogicDelFiled, TableInfo tableInfo, String shardingColumn) {
List<TableFieldInfo> fieldList = tableInfo.getFieldList();
// 去掉分表字段的set设置,即不修改分表字段
String rmShardingColumnSet = fieldList.stream()
.filter(i -> ignoreLogicDelFiled ? !(tableInfo.isLogicDelete() && i.isLogicDelete()) : true)
.filter(i -> !i.getColumn().equals(shardingColumn))
.map(i -> i.getSqlSet(ENTITY_DOT))
.filter(Objects::nonNull).collect(joining(NEWLINE));
return rmShardingColumnSet;
}
}
3.定义一个sql注入器GyhSqlInjector,添加UpdateByIdWithSharding对象
// 需注入到spring容器中
@Component
public class GyhSqlInjector extends DefaultSqlInjector {
/**
* shardingsphere 配置信息
*/
@Autowired
private YamlShardingRuleConfiguration yamlShardingRuleConfiguration;
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
// 添加 UpdateByIdWithSharding 对象,并注入分库分表信息
methodList.add(new UpdateByIdWithSharding(yamlShardingRuleConfiguration));
return methodList;
}
}
4.定义一个基础MapperGyhBaseMapper,添加新的selectById方法
/**
* 自定义的通用Mapper
*/
public interface GyhBaseMapper<T> extends BaseMapper<T> {
int updateById(@Param(Constants.ENTITY) T entity);
}
5.所有参与分表的表,在定义Mapper时继承GyhBaseMapper,那么在使用他的updateById方法时,将自动增加分库分表判断,准确命中目标表,减少其他分表查询的资源浪费。
以上是针对mybatisplus的一些简单改造,希望能为你提供一点点帮助~
作者:京东科技 郭艳红
来源:京东云开发者社区 转载请注明来源
手把手教你如何扩展(破解)mybatisplus的sql生成的更多相关文章
- 手把手教你Chrome扩展开发:本地存储篇
手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单 手把手教你开发Chrome扩展二:为html添加行为 手把手教你开发Chrome扩展三:关于本地存储数据 HTML5 ...
- 【前端工具】Chrome 扩展程序的开发与发布 -- 手把手教你开发扩展程序
关于 chrome 扩展的文章,很久之前也写过一篇.清除页面广告?身为前端,自己做一款简易的chrome扩展吧. 本篇文章重在分享一些制作扩展的过程中比较重要的知识及难点. 什么是 chrome 扩展 ...
- ----转载----【前端工具】Chrome 扩展程序的开发与发布 -- 手把手教你开发扩展程序
关于 chrome 扩展的文章,很久之前也写过一篇.清除页面广告?身为前端,自己做一款简易的chrome扩展吧. 本篇文章重在分享一些制作扩展的过程中比较重要的知识及难点. 什么是 chrome 扩展 ...
- 手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单
手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单 手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单 手把手教你开发Chrome扩 ...
- 菜鸟-手把手教你把Acegi应用到实际项目中(8)-扩展UserDetailsService接口
一个能为DaoAuthenticationProvider提供存取认证库的的类,它必须要实现UserDetailsService接口: public UserDetails loadUserByUse ...
- 手把手教你开发chrome扩展
转载:http://www.cnblogs.com/walkingp/archive/2011/04/04/2003875.html 手把手教你开发chrome扩展一:开发Chrome Extenst ...
- 手把手教你开发Chrome扩展三:关于本地存储数据
手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单 手把手教你开发Chrome扩展二:为html添加行为 手把手教你开发Chrome扩展三:关于本地存储数据 HTML5 ...
- 手把手教你开发Chrome扩展二:为html添加行为
手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单 手把手教你开发Chrome扩展二:为html添加行为 手把手教你开发Chrome扩展三:关于本地存储数据 上一节我们 ...
- 手把手教你破解文件密码、wifi密码、网页密码
手把手教你破解文件密码.wifi密码.网页密码 1.破解文件密码: 有时候我们在网上下载一个压缩包后,必须要关注或者支付一定费用才给你解压密码,实属比较恶心.在这里手把手叫你实现破解文件解压密码. 1 ...
- 手把手教从零开始在GitHub上使用Hexo搭建博客教程(二)-Hexo参数设置
前言 前文手把手教从零开始在GitHub上使用Hexo搭建博客教程(一)-附GitHub注册及配置介绍了github注册.git相关设置以及hexo基本操作. 本文主要介绍一下hexo的常用参数设置. ...
随机推荐
- Linux中的进程页表
是什么 进程页表是用于管理进程虚拟地址空间和物理内存之间映射关系的数据结构.它记录了进程中每个虚拟页对应的物理页的信息. 什么作用 进程使用进程页表的方式是通过虚拟地址访问内存.当进程访问一个虚拟地址 ...
- linux 查看进程使用的内存大小
你可以使用 ps 命令结合 grep 命令来查看进程使用的内存大小.以下是示例代码: ps aux | grep <进程名> 这个命令会列出所有匹配 <进程名> 的进程,并显示 ...
- 【go语言】2.4.2 自定义包的创建和使用
在 Go 中,任何一个目录都可以被视为一个包.创建自定义包的基本步骤是: 新建一个目录,用于存放包的源文件. 在新建的目录中编写 Go 代码,代码的第一行应该是 package 包名. 使用 impo ...
- python教程 入门学习笔记 第3天 编程基础常识 代码注释 变量与常量
编程基础常识 一.注释 1.对代码的说明与解释,它不会被编译执行,也不会显示在编译结果中 2.注释分为:单行注释和多行注释 3.用#号开始,例如:#这是我的第一个python程序 4.注释可以写在单独 ...
- 从 Pulsar Client 的原理到它的监控面板
背景 前段时间业务团队偶尔会碰到一些 Pulsar 使用的问题,比如消息阻塞不消费了.生产者消息发送缓慢等各种问题. 虽然我们有个监控页面可以根据 topic 维度查看他的发送状态,比如速率.流量.消 ...
- python处理类似json的文件
前言 有些文件长得像json的键值对格式,但又不完全是.有时需要提取出其中某些值,可以先手动处理成json文件,然后用python的json模块. 示例1:每行键值对 提取其中的caseId的值 {& ...
- 记录一次AutoMapper注册报错
通常,.Net5我们注册服务是这样的. //添加AutoMapper var automapperConfog = new MapperConfiguration(config => { con ...
- 按关键字API接口搜索天眼查企业数据
一.如果你想要查找某一个企业的基本信息或是对行业中的企业进行筛选,那么使用API接口搜索天眼查企业数据会非常方便. 首先,你需要获取天眼查API的access_token,这可以通过注册账号获取.一旦 ...
- CodeForces 1343D Constant Palindrome Sum
题意 多组样例 给一个长度为\(n\)(\(n\)一定为偶数)的数组\(a[]\),给一个正整数\(k\),保证数组内元素为小于等于\(k\)的正整数,你可以每次将数组的一个元素变为小于等于\(k\) ...
- QA|4个数据打开了4个页面,怎么实现只打开一个页面?单例模式|网页计算器自动化测试实战
如下图,代码中4个数据,产生了4个页面,怎么实现只打开一个页面?可使用单例模式 查询得知 单例模式实现有5种方法,参照链接下: https://blog.csdn.net/SixStar_FL/art ...