Mybatis Generator Plugin 定制我需要的DAO

在上一篇文章我的Spring多数据源中提到对Mybatis Generator Plugin的开发改造,今天就上次示例中的一些细节点做一些描述介绍。

首先,先要理解Mybatis Generator Plugin,建议先阅读 小码哥Java学院理解MyBatis Generator Plugin
同样,在 http://generator.sturgeon.mopaas.com/reference/pluggingIn.html 也有详细的介绍,相信看了这些资料,对于Mybatis Generator Plugin 插件的理解和开发已经不是什么困难的事情了。

那么接下来就上文中的分页参数的使用以及多数据源注解的自动生成做一些介绍。
PS:本文使用的是注解方式,如果使用XMLMAPPER方式的本文仅供参考,其实大同小异并没太大区别。

创建自己的插件 —— MysqlGeneratorPlug

1、继承PluginAdapter

  public class MysqlGeneratorPlug extends PluginAdapter 

2、为Example添加分页参数offset、limit、resultColumn属性。resultColumn属性使用在当查询数据我们并不需要全表返回而是个别几个字段的时候使用,如 SELECT id,name,age FROM user_base 这种情况下。

@Overridepublic boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {    
  addLimit(topLevelClass, introspectedTable, "offset");    
  addLimit(topLevelClass, introspectedTable, "limit");    
  addResultColumn(topLevelClass, introspectedTable, "resultColumn");    
  return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
}
private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
    CommentGenerator commentGenerator = getContext().getCommentGenerator();
    Field field = new Field();    field.setVisibility(JavaVisibility.PROTECTED);
    field.setType(FullyQualifiedJavaType.getIntInstance());    field.setName(name);
    field.setInitializationString("-1");    commentGenerator.addFieldComment(field, introspectedTable);
    topLevelClass.addField(field);
    char c = name.charAt(0);
    String camel = Character.toUpperCase(c) + name.substring(1);
    Method method = new Method();
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setName("set" + camel);
    method.addParameter(new Parameter(FullyQualifiedJavaType.getIntInstance(), name));
    method.addBodyLine("this." + name + "=" + name + ";");
    commentGenerator.addGeneralMethodComment(method, introspectedTable);
    topLevelClass.addMethod(method);
    method = new Method();
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setReturnType(FullyQualifiedJavaType.getIntInstance());
    method.setName("get" + camel);
    method.addBodyLine("return " + name + ";");
    commentGenerator.addGeneralMethodComment(method, introspectedTable);
    topLevelClass.addMethod(method);
}
private void addResultColumn(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
    CommentGenerator commentGenerator = getContext().getCommentGenerator();
    Field field = new Field();
    field.setVisibility(JavaVisibility.PROTECTED);
    field.setType(FullyQualifiedJavaType.getStringInstance());
    field.setName(name);
    commentGenerator.addFieldComment(field, introspectedTable);
    topLevelClass.addField(field);
    char c = name.charAt(0);
    String camel = Character.toUpperCase(c) + name.substring(1);
    Method method = new Method();
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setName("set" + camel);
    method.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), name));
    method.addBodyLine("this." + name + "=" + name + ";");
    commentGenerator.addGeneralMethodComment(method, introspectedTable);
    topLevelClass.addMethod(method);    method = new Method();
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setReturnType(FullyQualifiedJavaType.getStringInstance());
    method.setName("get" + camel);
    method.addBodyLine("return " + name + ";");
    commentGenerator.addGeneralMethodComment(method, introspectedTable);
    topLevelClass.addMethod(method);
}
Paste_Image.png

如上,offset、limit以及resultColumn 属性以及get、set 方法均以创建完成。
那么接下来需要在对应的SqlProvider中使其起作用,则需要修改对应的实现方法。

参照下原版生成出来的 countByExample

Paste_Image.png

原版生成的selectByExample

Paste_Image.png

很显然这样使用并不方便,select 返回了所有的字段,而且也没有分页 可用性并不强,而需要改造的,也只是将我们需要查询的字段传递进来,以及增加分页功能而已。理解了原版生成的规则,我们就可以开始定制我们所需要的功能。

修改countByExample,是其增加指定列以及分页功能(其实count为什么要加上分页我也不明白,只是顺手而已 _

@Overridepublic boolean providerCountByExampleMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
    List<String> bodyLines = method.getBodyLines();
    //将原有第二句更改为 如果列名不为空,则使用列名   否则为 *    String sql = bodyLines.get(1);
    sql = sql.replace("*", "\" + (example.getResultColumn() == null || example.getResultColumn().isEmpty() ? \"*\" : example.getResultColumn()) + \"");
    bodyLines.set(1, sql);
    addLimit(bodyLines);
    return super.providerCountByExampleMethodGenerated(method, topLevelClass, introspectedTable);
}

修改selectByExample

@Overridepublic boolean providerSelectByExampleWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
    List<String> bodyLines = method.getBodyLines();
    repleaseSelectColumn(bodyLines);
    addLimit(bodyLines);
    return super.providerSelectByExampleWithoutBLOBsMethodGenerated(method, topLevelClass, introspectedTable);
}
private void addLimit(List<String> bodyLines) {
    int lastIndex = bodyLines.size() - 1;
    //先移除最后一行
    bodyLines.remove(lastIndex);
    //添加Limit 语句
    bodyLines.add("StringBuilder sqlBuilder = new StringBuilder(sql.toString());");
    bodyLines.add("if (example != null && example.getOffset() >= 0) {");
    bodyLines.add("sqlBuilder.append(\" LIMIT \").append(example.getOffset());");
    bodyLines.add("if (example.getLimit() > 0) {");
    bodyLines.add("sqlBuilder.append(\",\").append(example.getLimit());");
    bodyLines.add("}");
    bodyLines.add("}");
    bodyLines.add("return sqlBuilder.toString();");
}
private void repleaseSelectColumn(List<String> bodyLines) {
    bodyLines.add(1, "if (example != null && example.getResultColumn() != null && !example.getResultColumn().isEmpty()){");
    bodyLines.add(2, "sql.SELECT(example.getResultColumn());");
    bodyLines.add(3, "} else {");
    int lastIndex = 0;
    for (int i = 0; i < bodyLines.size(); i++) {
        if (bodyLines.get(i).indexOf("SELECT") > 0) lastIndex = i;
    }
    bodyLines.add(lastIndex + 1, "}");
}

经此改动后,生成的 countByExample 以及 selectByExample

Paste_Image.png
Paste_Image.png

这样,我们对于分页以及增加只返回需要的字段功能便已完成,其中selectByExampleWithBLOBs与selectByExample相似度几乎一致,就不贴代码了 _

接下来介绍下 我的Spring多数据源 中提到的主从注解以及多数据源注解在插件中使其自动生成出来
在generator.xml中增加自定义配置,表示此次生成的对应哪个数据源,默认数据源可不需要此配置

<property name="dataSource" value="shop"/>
@Overridepublic boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
    //获取是否其他数据源,如果是,则增加其他数据源的配置
    String ortherSource = context.getProperties().getProperty("dataSource");
    interfaze.addImportedType(new FullyQualifiedJavaType("com.design.datasource.invocation.Read"));
    interfaze.addImportedType(new FullyQualifiedJavaType("com.design.datasource.invocation.Write"));
    if (ortherSource != null && !ortherSource.isEmpty()) {
        interfaze.addImportedType(new FullyQualifiedJavaType("com.design.datasource.invocation.OtherSource"));
    }
    for (Method method : interfaze.getMethods()) {
        String methodName = method.getName();
        if (methodName.startsWith("count") || methodName.startsWith("select")) {
            method.addAnnotation("@Read");
        } else {
            method.addAnnotation("@Write");
        }
        if (ortherSource != null && !ortherSource.isEmpty()) {
            method.addAnnotation("@OtherSource(\"" + ortherSource + "\")");
        }
    }
    return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
}

生成后的 Mapper

Paste_Image.png
Paste_Image.png

就这么简单,增加其他数据源的配置读取,过滤所有方法 只要是count 和 select 的 就认为是从库 其他均为主库。如果实在需要从主库查询的,可以在Mapper中手动调整即可,是不是很方便了 哈哈 _

最后提一下,要使插件生效很简单,只是在generator.xml 的 <context> 节点 中添加插件引用即可

<plugin type="com.design.mybatis.generator.MysqlGeneratorPlug"/>

至此,Spring Mybatis 多数据源 主从 自动切换,以及查询分页,根据需要返回查询字段数据均以完成,一切都是直接生成出来的 _
我先自己暗爽会儿,写的不好敬请拍砖,不喜勿喷 哈哈~~~!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,422评论 0 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,287评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • 杨柳撩起长发 荷花含情脉脉 你从河心撑船过 娇艳 美丽 炙热的心催水涨 我心要多广阔 才能容下这山河 浮萍织起罗绮...
    左锦兰可乐阅读 266评论 0 1
  • 中医在两千多年前就已形成了基本理论,在接下来漫长的历史长河中,中医的理论被不断补充,经验不断增加,最终形成了独立完...
    佳年风华阅读 20,463评论 24 29