Mybatis-Generator 扩展支持链式编程

2019-05-17  本文已影响0人  灵技阁

上次,有同事问我,现在链式编程已经很普遍了,自动生成的set方法一般都不支持链式,有没有什么好的办法呢?

其实,我们在使用lombok@Setter的时候,同时添加@Accessors(chain = true)注解,被注解的对象就自动支持链式了.

这里要说的是,在我们使用Mybatis-Generator反向生成代码时,如何使生成的model支持链式呢?

我们知道,Mybatis-Generator提供了PluginAdapter让我们进行扩展(此类请读者自行了解,这里不再进行介绍),而类中,我们可以看到,PluginAdapter有一个方法modelSetterMethodGenerated,显然,我们通过命名就已经得知此方法是model的setter方法生成扩展.
由此,我们可以尝试下:

/**
 *
 *
 * @author Marvis
 * @ClassName EntityChainPlugin
 * @Description
 */
public class EntityChainPlugin extends PluginAdapter {

    @Override
    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass,
                                              IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable,
                                              ModelClassType modelClassType) {

        method.setReturnType(topLevelClass.getType());
        method.addBodyLine("return this;");
        return super.modelSetterMethodGenerated(method, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }

    /**
     * This plugin is always valid - no properties are required
     */
    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }
}

然后在generatorConfig.xml中的<context>标签节点下添加:

<plugin type="run.override.EntityChainPlugin "/>

好了,运行跑跑看:

@SuppressWarnings("serial")
public class Agent implements Serializable {
   //   ....省略...
    /**
     * @param id : ID
     */
    public Agent setId(Long id) {
        this.id = id;
        return this;
    }
     // ....省略...
}

得到了我们想要的效果.
完事,收工~~嘿嘿嘿

上一篇 下一篇

猜你喜欢

热点阅读