Mybatis生成器插件扩展,生成findInSet方法

Mybatis生成器插件扩展,生成findInSet方法 

public Criteria andNameFindInSet(String value) {addCriterionPattern("find_in_set($value, `name`)", value, "name");return (Criteria) this;}public Criteria andNamePattern(String pattern, String value) {addCriterionPattern(pattern.replace("##column##", "`name`"), value, "name");return (Criteria) this;}

 

一、生成模式原理

(1)Example.Criterion添加pattern字段

 public static class Criterion {private String condition;private Object value;private Object secondValue;private boolean noValue;private boolean singleValue;private boolean betweenValue;private boolean listValue;private String typeHandler;private boolean pattern;
}

(2)Example.GeneratedCriteria加方法addCriterionPattern

protected abstract static class GeneratedCriteriaprotected void addCriterionPattern(String condition, Object value, String property) {if (value == null) {throw new RuntimeException("Value for " + property + " cannot be null");}Criterion c = new Criterion(condition, value);c.setPattern(true);criteria.add(c);}
}

(3) 加对应列FindInSet方法

protected abstract static class GeneratedCriteria {public Criteria andXXXFindInSet(String value) {addCriterionPattern("find_in_set(##value##, `xxx`)", value, "xxx");return (Criteria) this;}
}

(4)改造XXXSqlProvider.applyWhere的 if (criterion.isNoValue()) 前增加模式代码

if (criterion.isPattern()) {String value;if (criterion.getTypeHandler() == null) {value = String.format(parmPhrase1, "", i, j).trim();} else {value = String.format(parmPhrase1_th, "", i, j, criterion.getTypeHandler()).trim();}sb.append(criterion.getCondition().replaceAll("##value##", value));
} else if (criterion.isNoValue()) {sb.append(criterion.getCondition());
} else if (criterion.isSingleValue()) {}

(5)改造XXXMapper.xml的<when test="criterion.noValue">前增加模式代码

<when test="criterion.pattern">and<foreach collection="criterion.condition.split('##value##')" item="criterionCond" separator="#{criterion.value}">${criterionCond}</foreach>
</when>
<when test="criterion.noValue">and ${criterion.condition}
</when>

 

二、插件代码

package com.mk.mybatisgenerator.plugins;import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.ibatis2.Ibatis2FormattingUtilities;
import java.util.ArrayList;
import java.util.List;public class MySQLMethodPlugin extends PluginAdapter {private final String valueName = "##value##";//值占位符private final String columnName = "##column##";//列名占位符public MySQLMethodPlugin() {super();}@Overridepublic boolean validate(List<String> warnings) {return true;}/*** 重写example* @param topLevelClass* @param introspectedTable* @return*/@Overridepublic boolean modelExampleClassGenerated(TopLevelClass topLevelClass,IntrospectedTable introspectedTable) {addCriterionPattern(topLevelClass, introspectedTable);//增加模式匹配addFindInSet(topLevelClass, introspectedTable);//增加find_in_set方法addPattern(topLevelClass,  introspectedTable);//增加模式方法return true;}/*** xml ExampleWhere重写* @param element* @param introspectedTable* @return*/@Overridepublic boolean sqlMapExampleWhereClauseElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {XmlElement whereElement = (XmlElement) element.getElements().get(0);XmlElement foreachElement = (XmlElement) whereElement.getElements().get(0);XmlElement ifElement = (XmlElement) foreachElement.getElements().get(0);XmlElement trimElement = (XmlElement) ifElement.getElements().get(0);XmlElement foreachCriteriaElement = (XmlElement) trimElement.getElements().get(0);XmlElement chooseElement = (XmlElement) foreachCriteriaElement.getElements().get(0);for (Element ele : chooseElement.getElements()) {XmlElement noValueElement = (XmlElement) ele;for (Attribute attribute : noValueElement.getAttributes()) {//找到criterion.noValue行插入模式代码if (attribute.getName().equals("test") && attribute.getValue().equals("criterion.noValue")) {XmlElement patternElement = new XmlElement("when");patternElement.addAttribute(new Attribute("test", "criterion.pattern"));//<foreach collection="oredCriteria" item="criteria" separator="or">XmlElement forElement = new XmlElement("foreach");forElement.addAttribute(new Attribute("collection", "criterion.condition.split('" + valueName + "')"));forElement.addAttribute(new Attribute("item", "criterionCond"));forElement.addAttribute(new Attribute("separator", "#{criterion.value}"));forElement.addElement(new TextElement("${criterionCond}"));patternElement.addElement(new TextElement("and"));patternElement.addElement(forElement);chooseElement.addElement(0, patternElement);return true;}}}throw new RuntimeException("ChooseElement not exist");}/*** 重写ApplyWhere方法* @param method* @param topLevelClass* @param introspectedTable* @return*/@Overridepublic boolean providerApplyWhereMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {List<String> lines = method.getBodyLines();for (int i = 0, len = lines.size(); i < len; i++) {String line = lines.get(i).trim();//找到criterion.noValue行插入模式代码if (line.matches("if\\s*\\(criterion\\.isNoValue\\(\\)\\)\\s*\\{")) {lines.remove(i);List<String> appends = new ArrayList<>();appends.add("if (criterion.isPattern()) {");appends.add("String value;");appends.add(" if (criterion.getTypeHandler() == null) {");appends.add("value = String.format(parmPhrase1, \"\", i, j).trim();");appends.add("} else {");appends.add("value = String.format(parmPhrase1_th, \"\", i, j, criterion.getTypeHandler()).trim();");appends.add("}");appends.add("sb.append(criterion.getCondition().replaceAll(\"" + valueName + "\", value));");appends.add("} else " + line);method.addBodyLines(i, appends);return true;}}throw new RuntimeException("criterion.isNoValue() not exist");}/*protected void addCriterionPattern(String condition, Object value, String property) {if (value == null) {throw new RuntimeException("Value for " + property + " cannot be null");}Criterion c = new Criterion(condition, value);c.setPattern(true);criteria.add(c);}*/public void addCriterionPattern(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {addCriterionPatternField(topLevelClass, introspectedTable);InnerClass criteria = null;// first, find the Criteria inner classfor (InnerClass innerClass : topLevelClass.getInnerClasses()) {if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$criteria = innerClass;break;}}if (criteria == null) {throw new RuntimeException("GeneratedCriteria not exist");}Method method = new Method();method.setVisibility(JavaVisibility.PROTECTED);method.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "condition"));method.addParameter(new Parameter(FullyQualifiedJavaType.getObjectInstance(), "value"));method.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "property"));method.setName("addCriterionPattern");method.addBodyLine("if (value == null) {");method.addBodyLine("throw new RuntimeException(\"Value for \" + property + \" cannot be null\");");method.addBodyLine("}");method.addBodyLine("Criterion c = new Criterion(condition, value);");method.addBodyLine("c.setPattern(true);");method.addBodyLine("criteria.add(c);");criteria.addMethod(method);}public void addCriterionPatternField(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {InnerClass criterion = null;// first, find the Criteria inner classfor (InnerClass innerClass : topLevelClass.getInnerClasses()) {if ("Criterion".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$criterion = innerClass;break;}}if (criterion == null) {throw new RuntimeException("Criterion not exist");}FullyQualifiedJavaType booleanPrimitive = FullyQualifiedJavaType.getBooleanPrimitiveInstance();Field pattern = new Field();pattern.setName("pattern");pattern.setVisibility(JavaVisibility.PRIVATE);pattern.setType(booleanPrimitive);criterion.addField(pattern);Method setPattern = new Method();setPattern.setVisibility(JavaVisibility.PUBLIC);setPattern.setName("setPattern");setPattern.addParameter(new Parameter(booleanPrimitive, "pattern"));setPattern.addBodyLine("this.pattern = pattern;");criterion.addMethod(setPattern);Method isPattern = new Method();isPattern.setVisibility(JavaVisibility.PUBLIC);isPattern.setReturnType(booleanPrimitive);isPattern.setName("isPattern");isPattern.addBodyLine("return pattern;");criterion.addMethod(isPattern);}public void addFindInSet(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {addFindInSetPattern(topLevelClass, introspectedTable, "findInSet", "find_in_set(" + valueName + ", " + columnName + ")");}public void addFindInSetPattern(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String opName, String pattern) {InnerClass criteria = null;// first, find the Criteria inner classfor (InnerClass innerClass : topLevelClass.getInnerClasses()) {if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$criteria = innerClass;break;}}if (criteria == null) {throw new RuntimeException("GeneratedCriteria not exist");}for (IntrospectedColumn introspectedColumn : introspectedTable.getNonBLOBColumns()) {if (!introspectedColumn.isJdbcCharacterColumn()|| !introspectedColumn.isStringColumn()) {continue;}Method method = new Method();method.setVisibility(JavaVisibility.PUBLIC);method.addParameter(new Parameter(introspectedColumn.getFullyQualifiedJavaType(), "value")); //$NON-NLS-1$StringBuilder opNameBuilder = new StringBuilder(opName);opNameBuilder.setCharAt(0, Character.toUpperCase(opNameBuilder.charAt(0)));opName = opNameBuilder.toString();StringBuilder sb = new StringBuilder();sb.append(introspectedColumn.getJavaProperty());sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));sb.insert(0, "and"); //$NON-NLS-1$sb.append(opName);method.setName(sb.toString());method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance());sb.setLength(0);sb.append("addCriterionPattern(\"").append(pattern.replaceAll(columnName, Ibatis2FormattingUtilities.getAliasedActualColumnName(introspectedColumn))).append("\", value, \"").append(introspectedColumn.getJavaProperty());sb.append("\");");method.addBodyLine(sb.toString());method.addBodyLine("return (Criteria) this;");criteria.addMethod(method);}}public void addPattern(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {addPatternMethod(topLevelClass, introspectedTable, "pattern");}public void addPatternMethod(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String opName){InnerClass criteria = null;// first, find the Criteria inner classfor (InnerClass innerClass : topLevelClass.getInnerClasses()) {if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$criteria = innerClass;break;}}if (criteria == null) {throw new RuntimeException("GeneratedCriteria not exist");}for (IntrospectedColumn introspectedColumn : introspectedTable.getNonBLOBColumns()) {if (!introspectedColumn.isJdbcCharacterColumn()|| !introspectedColumn.isStringColumn()) {continue;}Method method = new Method();method.setVisibility(JavaVisibility.PUBLIC);method.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "pattern"));method.addParameter(new Parameter(introspectedColumn.getFullyQualifiedJavaType(), "value"));StringBuilder opNameBuilder = new StringBuilder(opName);opNameBuilder.setCharAt(0, Character.toUpperCase(opNameBuilder.charAt(0)));opName = opNameBuilder.toString();StringBuilder sb = new StringBuilder();sb.append(introspectedColumn.getJavaProperty());sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));sb.insert(0, "and"); //$NON-NLS-1$sb.append(opName);method.setName(sb.toString());method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance());sb.setLength(0);sb.append("addCriterionPattern(pattern.replaceAll(\"").append(columnName).append("\", \"").append(Ibatis2FormattingUtilities.getAliasedActualColumnName(introspectedColumn)).append("\")").append(", value, \"").append(introspectedColumn.getJavaProperty());sb.append("\");");method.addBodyLine(sb.toString());method.addBodyLine("return (Criteria) this;");criteria.addMethod(method);}}}

 

三、配置插件

<plugin type="com.mk.mybatisgenerator.plugins.MySQLMethodPlugin"/>

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/322334.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[认证授权] 6.Permission Based Access Control

在前面5篇博客中介绍了OAuth2和OIDC&#xff08;OpenId Connect&#xff09;&#xff0c;其作用是授权和认证。那么当我们得到OAuth2的Access Token或者OIDC的Id Token之后&#xff0c;我们的资源服务如何来验证这些token是否有权限来执行对资源的某一项操作呢&#xff1f;比如…

P4841,jzoj3303-城市规划【NTT,多项式求逆,dp】

正题 题目链接:https://www.luogu.org/problemnew/show/P4841 题目大意 求nnn个点的简单联通无向图的个数。 解题思路 首先考虑n2n^2n2&#xff0c;我们设gig_igi​表示iii个点的简单无向图的个数&#xff0c;显然gi2n(n−1)2g_i2^{\frac{n(n-1)}{2}}gi​22n(n−1)​ 然后我…

微软发布PowerShell Core第一个版本:支持多平台开发

微软旗下的PowerShell团队正式宣布推出PowerShell Core 6.0&#xff0c;非常诡异的是这明明是Core的第一个版本&#xff0c;但是却用了一个6.0后缀的版本号。“这是我们对PowerShell做出的最大最重要的改变&#xff01;”微软技术研究员兼PowerShell创始人Jeffrey Snover在Twit…

Mybatis生成器插件扩展,定制方法生成,list参数生成

Mybatis生成器插件扩展&#xff0c;定制方法生成 public Criteria andNameIsEmpty() {addCriterion("name ");setCriterionPattern();return (Criteria) this;}public Criteria andNameFindInSet(String value) {addCriterion("find_in_set($value, name)"…

欢乐纪中某A组赛【2019.7.5】

前言 被花式暴虐&#xff0c;T1T1T1签到后两题神仙 成绩 JJJ表示初中&#xff0c;HHH表示高中后面加的是几年级 RankRankRankPersonPersonPersonScoreScoreScoreAAABBBCCC111(J−3)ZZY(J-3)ZZY(J−3)ZZY200200200100100100100100100000888(J−3)WHF(J-3)WHF(J−3)WHF145145145…

Mybatis生成器插件扩展,生成OR操作

Mybatis生成器插件扩展&#xff0c;生成OR操作 ManExample example new ManExample();ManExample.Criteria and example.createCriteria();and.andNameIsEmpty().andNameFindInSet("a").andNameFindInSetIn(Arrays.asList("1", "2", "3&q…

.NET Core单文件发布静态编译AOT CoreRT

.NET Core单文件发布静态编译AOT CoreRT&#xff0c;将.NET Core应用打包成一个可执行文件并包含运行时。支持Windows, MacOS and Linux x64 w/ RyuJIT codegen。示例项目&#xff1a;https://github.com/dotnet/corert/tree/master/samples/WebApi下面来实际体验。首先确保安装…

2019纪中暑假游记+总结

Travels总篇\texttt{Travels总篇}Travels总篇 7/4\texttt{7/4}7/4 下午才去纪中&#xff0c;早上就一大早和同学出去玩&#xff0c;看了蜘蛛侠然后到3点多才出发。 因为走南沙大桥所以很快就到了(具体有多快忘了&#xff0c;反正路上一点都不塞车)。就愉快的去整理宿舍洗个早…

使用xUnit为.net core程序进行单元测试(上)

一. 导读为什么要编写自动化测试程序&#xff08;Automated Tests&#xff09;&#xff1f;可以频繁的进行测试可以在任何时间进行测试&#xff0c;也可以按计划定时进行&#xff0c;例如&#xff1a;可以在半夜进行自动测试。肯定比人工测试要快。可以更快速的发现错误。基本上…

select2删除选中项,allowClear设置

转载自 select2删除选中项&#xff0c;allowClear设置 在使用select2过程中&#xff0c;有时候需要删除我们选中的选项&#xff0c;如下图&#xff1a; 这时候就需要设置select2的allowClear属性了。 有两种方法&#xff1a; 第一种&#xff1a; 直接用select2定义的一个c…

jzoj2679-跨时代【背包,dfs,状压】

正题 题目大意 若干根棍子&#xff0c;不能折&#xff0c;不能多余求能够组成的最大长方形。 解题思路 首先我们发现如果棍子集合SSS长度为lll且它有子集GGG长度为l2\frac{l}{2}2l​那么就表示这个集合的棍子可以作为一个矩形的对应两边&#xff0c;这样我们只要枚举两个不相…

LeetCode算法总结-回溯法与深度优先搜索

转载自 LeetCode算法总结-回溯法与深度优先搜索 回溯法&#xff08;探索与回溯法&#xff09;是一种选优搜索法&#xff0c;又称为试探法&#xff0c;按选优条件向前搜索&#xff0c;以达到目标。但当探索到某一步时&#xff0c;发现原先选择并不优或达不到目标&#xff0c;就…

Mybatis的配置与使用

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录前言一、Mybatis所用jar包二、使用步骤1.配置mybatis.xml文件2.创建与数据库对应的po类&#xff0c;提供get、set、toString方法3.创建与Dept对应的接口类&#xff1…

入门干货之用DVG打造你的项目主页-Docfx、Vs、Github

由于这三项技术涉及到的要点以及内容较多&#xff0c;希望大家有空能自己挖掘一下更多更深的用法。0x01、介绍VS&#xff0c;即VS2017以及以上版本&#xff0c;宇宙最好的IDE&#xff0c;集成了宇宙最有前景的平台&#xff0c;前阶段也支持了宇宙最好的语言。Github&#xff0c…

P2579,jzoj2288-[ZJOI2005]沼泽鳄鱼【矩阵乘法】

正题 题目链接:https://www.luogu.org/problemnew/show/P2579 题目大意 一张无向图&#xff0c;一个起点一个终点。 有食人鱼&#xff0c;在若干个点之间有周期的移动&#xff0c;周期为222或333或444个点为循环。 然后要求从起点到终点走kkk步且不碰到食人鱼的方案数。 解…

ASP.NET Core中使用IOC三部曲(一.使用ASP.NET Core自带的IOC容器)

前言本文主要是详解一下在ASP.NET Core中,自带的IOC容器相关的使用方式和注入类型的生命周期.这里就不详细的赘述IOC是什么 以及DI是什么了.. emm..不懂的可以自行百度.正文今天我们主要讲讲如何使用自带IOC容器,emm..虽然自带的功能不是那么强大,但是胜在轻量级..而且..不用引…

P4130,jzoj1214-[NOI2007]项链工厂【线段树】

正题 题目链接:https://www.luogu.org/problemnew/show/P4130 题目大意 一个环形颜色珠子链&#xff0c;位置(注意不是上面的珠子)从最上顺时针下来位置依次标号1∼n1\sim n1∼n。 然后要求支持以下操作 Rk:R\ k:R k:将所有珠子顺时针旋转kkk个。F:F:F:将所有珠子以111向下翻…

LeetCode常用算法模式大厂面试题整理

转载自 LeetCode常用算法模式&大厂面试题整理 文章目录 1、滑动窗口 2、双指针 3、快慢指针 4、合并区间 5、循环排序 6、就地反转链表 7、堆-优先队列问题 8、Top K 9、归并 10、单调栈 11、回溯法 BATJ等大厂面试真题汇总 1、滑动窗口 1 一个左指针&#xff0c;一个右…

ABPZero系列教程之拼多多卖家工具

此系列文章围绕着拼多多卖家工具来介绍ABPZero的使用&#xff0c;内容包括手机登录、手机注册、拼团提醒、微信公众号绑定帐号、有拼团发送消息到微信公众号&#xff08;只要关注过微信公众号并已绑定系统帐号&#xff09;。学习此系列必备&#xff1a;手机验证码&#xff1a;使…