mybatis逆向工程的增强插件

6月22日,主要就是再写一个mybatis逆向工程的插件,原本希望能实现自定义查询字段,后来使用插件发现不太好实现,所以我就用插件实现了一些别的功能,除了分页以外,还有,在实体类中加一个附加属性用于保存可能需要的东西,mapper文件里边加两个自定义的查询方法,并且在接口中也加上这两个对应的方法.要实现自定义查询字段的功能,最好是通过mybatis拦截器,但是由于我对这个不熟悉,以后有空了再研究


import java.util.List;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.ShellRunner;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

/**
 * <pre>
 * 张某松 2019年6月22日修改
 * add paginationusing mysql limit.2
 * This class isonly used in ibator code generator.
 *[generatorConfiguration]
 *     [context id="context1"]
 *            [plugintype="com.epublic.xzk.db.mybatis.plugin.PaginationPlugin" /]
 *
 * </pre>
 */
public class PaginationPluginGenerate extends PluginAdapter {
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass ,IntrospectedTable introspectedTable ) {
        // addfield, getter, setter for limit clause
        addLimit( topLevelClass , introspectedTable , "limitStart",FullyQualifiedJavaType.getIntInstance() );
        addLimit( topLevelClass , introspectedTable , "limitEnd",FullyQualifiedJavaType.getIntInstance() );
        addLimit( topLevelClass , introspectedTable , "group" ,FullyQualifiedJavaType.getStringInstance());
        addLimit( topLevelClass , introspectedTable , "fields"  ,FullyQualifiedJavaType.getStringInstance());
        return super .modelExampleClassGenerated( topLevelClass , introspectedTable );
    }

    @Override
    public boolean sqlMapResultMapWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return super.sqlMapResultMapWithoutBLOBsElementGenerated(element, introspectedTable);
    }

    /** 如果在接口中不能添加这些方法,可以通过sql会话模板进行操作
     * @param document
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        System.out.println(document);
        XmlElement selectCustomiz=new XmlElement("select");
        selectCustomiz.addAttribute(new Attribute("id","selectCustomiz"));
//        String tbName=introspectedTable.get
//        String exampleType=introspectedTable.getContext() .getJavaModelGeneratorConfiguration().getTargetPackage() + "." + interfaze.getType().getShortName().replace("Mapper", "Example");
        String exampleType=introspectedTable.getExampleType();//.getBaseRecordType()
        selectCustomiz.addAttribute(new Attribute("parameterType",exampleType));
        selectCustomiz.addAttribute(new Attribute("resultMap","map"));
        selectCustomiz.addElement(new TextElement("select \n") );
        XmlElement choose=new XmlElement("choose");
        XmlElement when=new XmlElement("when");
        when.addAttribute(new Attribute("test","fields !=null"));
        when.addElement(new TextElement("${fields}"));
        XmlElement otherwise=new XmlElement("otherwise");
        otherwise.addElement(new TextElement(" * "));
        choose.addElement(when);
        choose.addElement(otherwise);
        selectCustomiz.addElement(choose);
        selectCustomiz.addElement(new TextElement(" from  "+introspectedTable.getFullyQualifiedTableNameAtRuntime()));
        XmlElement where_Clause = new XmlElement( "if" ); //$NON-NLS-1$
        where_Clause .addAttribute( new Attribute( "test" , "_parameter != null  " ));
        XmlElement include = new XmlElement( "include" );
        include.addAttribute(new Attribute("refid","Example_Where_Clause"));
        where_Clause.addElement(include);
        selectCustomiz.addElement(where_Clause);
        XmlElement group = new XmlElement( "if" ); //$NON-NLS-1$
        group .addAttribute( new Attribute( "test" , "group != null  " )); //$NON-NLS-1$ //$NON-NLS-2$
        group .addElement( new TextElement( "group by ${group}  " ));
        selectCustomiz.addElement(group);
        XmlElement limit = new XmlElement( "if" ); //$NON-NLS-1$
        limit .addAttribute( new Attribute( "test" , "limitStart != null and limitStart >=0" )); //$NON-NLS-1$ //$NON-NLS-2$
        limit .addElement( new TextElement( "limit ${limitStart} , ${limitEnd}" ));
        selectCustomiz.addElement(limit);
        XmlElement selectBySql=new XmlElement("select");
        selectBySql.addAttribute(new Attribute("id","selectBySql"));
        selectBySql.addAttribute(new Attribute("parameterType","string"));
        XmlElement sql  = new XmlElement( "if" ); //$NON-NLS-1$
        sql  .addAttribute( new Attribute( "test" , "sql .trim() .toLowerCase().startsWith('select')  " )); //$NON-NLS-1$ //$NON-NLS-2$
        sql.addElement(new TextElement("${sql }"));//比较危险的方法 可查mysql.user密码
        selectBySql.addElement(sql);
        document.getRootElement().addElement(selectCustomiz);
        document.getRootElement().addElement(selectBySql);
        return super.sqlMapDocumentGenerated(document, introspectedTable);
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        System.out.println(interfaze);
//        topLevelClass.
        FullyQualifiedJavaType exampleType = new FullyQualifiedJavaType(introspectedTable.getExampleType());
//        FullyQualifiedJavaType exampleType = new FullyQualifiedJavaType(context.getJavaModelGeneratorConfiguration().getTargetPackage() + "." + interfaze.getType().getShortName().replace("Mapper", "Example"));
        if(exampleType==null)
             exampleType = new FullyQualifiedJavaType(context.getJavaModelGeneratorConfiguration().getTargetPackage() + "." + interfaze.getType().getShortName().replace("Mapper", "Example"));
        interfaze.addImportedType(FullyQualifiedJavaType.getNewListInstance());
//        interfaze.addImportedType(new FullyQualifiedJavaType(interfaze.getType()));
        interfaze.addImportedType(exampleType);
        Method selectCustomiz=new Method("selectCustomiz");
        selectCustomiz.setVisibility(JavaVisibility.PUBLIC);
        selectCustomiz.setReturnType(FullyQualifiedJavaType.getNewListInstance());
//        selectCustomiz.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance()," " ));
//        selectCustomiz.addParameter(new Parameter(FullyQualifiedJavaType.getCriteriaInstance(),"example"));
        selectCustomiz.addParameter(new Parameter(exampleType,"example"));
        Method selectBySql=new Method("selectBySql");
        selectBySql.setVisibility(JavaVisibility.PUBLIC);
        selectBySql.setReturnType(FullyQualifiedJavaType.getNewListInstance());
        selectBySql.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(),"sql" ));
//        selectBySql.addParameter(new Parameter(FullyQualifiedJavaType.getCriteriaInstance(),"example"));
        interfaze.addMethod(selectCustomiz);
        interfaze.addMethod(selectBySql);
        return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
    }

    @Override
    public boolean providerGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        System.out.println(topLevelClass);
        return super.providerGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element ,
                                                                     IntrospectedTable introspectedTable ) {
        System.out.println(element);
//        element.getElements()
        // LIMIT5,10; // 检索记录行 6-15
        XmlElement isNotNullElement = new XmlElement( "if" ); //$NON-NLS-1$
        isNotNullElement .addAttribute( new Attribute( "test" , "limitStart != null and limitStart >=0" )); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullElement .addElement( new TextElement( "limit ${limitStart} , ${limitEnd}" ));
        element .addElement( isNotNullElement );
        // LIMIT 5;// 检索前 5 个记录行

        return super .sqlMapUpdateByExampleWithoutBLOBsElementGenerated( element , introspectedTable );
    }

    //添加一个map/object用于放可能的其他属性
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        Field additional = new Field("additional", FullyQualifiedJavaType.getObjectInstance());
        additional.setVisibility(JavaVisibility.PUBLIC);
        topLevelClass.addField(additional);
        Method get=new Method("getAdditional");
        get.setVisibility(JavaVisibility.PUBLIC);
        get.setReturnType(FullyQualifiedJavaType.getObjectInstance());
        get.addBodyLine("return this.additional;");
        Method set=new Method("setAdditional");
        set.setVisibility(JavaVisibility.PUBLIC);
//        get.setReturnType(FullyQualifiedJavaType.void));
        set.addParameter(new Parameter(FullyQualifiedJavaType.getObjectInstance(),"additional"));
        set.addBodyLine("  this.additional= additional;");
        topLevelClass.addMethod(get);
        topLevelClass.addMethod(set);
        return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {

        XmlElement isNotNullOrderElement = new XmlElement( "if" ); //$NON-NLS-1$
        isNotNullOrderElement .addAttribute( new Attribute( "test" , "orderByClause != null " )); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullOrderElement .addElement( new TextElement( "order by ${orderByClause}  " ));
        element.addElement(isNotNullOrderElement);
        XmlElement isNotNullElement = new XmlElement( "if" ); //$NON-NLS-1$
        isNotNullElement .addAttribute( new Attribute( "test" , "limitStart != null and limitStart >=0" )); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullElement .addElement( new TextElement( "limit ${limitStart}  " ));
        element .addElement( isNotNullElement );
        return super.sqlMapUpdateByExampleSelectiveElementGenerated( element , introspectedTable );
    }
    @Override
    public boolean sqlMapUpdateByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {

        XmlElement isNotNullOrderElement = new XmlElement( "if" ); //$NON-NLS-1$
        isNotNullOrderElement .addAttribute( new Attribute( "test" , "orderByClause != null " )); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullOrderElement .addElement( new TextElement( "order by ${orderByClause}  " ));
        element.addElement(isNotNullOrderElement);
        XmlElement isNotNullElement = new XmlElement( "if" ); //$NON-NLS-1$
        isNotNullElement .addAttribute( new Attribute( "test" , "limitStart != null and limitStart >=0" )); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullElement .addElement( new TextElement( "limit ${limitStart}  " ));
        element .addElement( isNotNullElement );
        return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated( element , introspectedTable );
    }

    private void addLimit(TopLevelClass topLevelClass , IntrospectedTable introspectedTable , String name ,FullyQualifiedJavaType type){
        CommentGenerator commentGenerator = context .getCommentGenerator();
        Field field = new Field();
        field .setVisibility(JavaVisibility. PROTECTED );
        field .setType(type );
        field .setName( name );
        //默认值
        if(FullyQualifiedJavaType.getIntInstance().equals(type))
            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(type , name ));
        method .addBodyLine( "this." + name + "=" + name + ";" );
        commentGenerator .addGeneralMethodComment( method , introspectedTable );
        topLevelClass .addMethod( method );
        method = new Method();
        method .setVisibility(JavaVisibility. PUBLIC );
        method .setReturnType(type );
        method .setName( "get" + camel );
        method .addBodyLine( "return " + name + ";" );
        commentGenerator .addGeneralMethodComment( method , introspectedTable );
        topLevelClass .addMethod( method );
    }

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

    public static void generate() {
        String config = PaginationPluginGenerate. class .getClassLoader().getResource( "generatorConfig.xml" ).getFile();
        String[] arg = { "-configfile" , config , "-overwrite" };
        ShellRunner.main( arg );
    }

    public static void main(String[] args ) {
        com.mysql.jdbc.Driver driver=null;
        generate();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值