1. 程式人生 > >mybaits-generator生成中文註釋並帶分頁

mybaits-generator生成中文註釋並帶分頁

mybaits-generator修改的版本:1.3.4

org.mybatis.generator.core_1.3.4.201608190045.jar

修改原始碼路徑:

org.mybatis.generator.internal.DefaultCommentGenerator

修改後的jar下載地址:

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration > <!-- 設定mysql驅動路徑 --> <classPathEntry location="D:\ProgramData\jar_repo\mysql-jar\mysql-connector-java-5.1.30.jar" /> <!-- 此處指定生成針對MyBatis3的DAO --> <context id="context1" targetRuntime="MyBatis3"> <!-- 生成的Java檔案的編碼 -->
<property name="javaFileEncoding" value="UTF-8"/> <!-- 格式化java程式碼 --> <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/> <!-- 格式化XML程式碼 --> <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"
/>
<property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- 增加Models ToStirng方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" /> <!-- 增加愛Models Serializable實現 --> <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <!-- 分頁外掛 --> <!-- 在example類中增 page 屬性,並在mapper.xml的查詢中加入page !=null 時的查詢 --> <!-- <plugin type="org.mybatis.generator.plugins.MySQLPagerPlugin" /> --> <!-- 在example類中增 offset和limit屬性,並在mapper.xml的查詢中加入limit ${offset} , ${limit} 提供在offset和limit>0時的查詢 --> <plugin type="org.mybatis.generator.plugins.MySQLPaginationPlugin2"></plugin> <!--<plugin type="com.xxg.mybatis.plugins.MySQLLimitPlugin"></plugin>--> <commentGenerator> <!-- <property name="suppressDate" value="true"/> --> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="false"/> </commentGenerator> <!-- jdbc連線資訊 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/lee" userId="lee" password="eee" /> <!-- 生成bean和example物件 --> <javaModelGenerator targetPackage="arthur.dy.lee.model" targetProject="src/main/java" /> <!-- 生成mapper.xml類 --> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources" /> <!-- 生成DAO的類檔案以及配置檔案 --> <javaClientGenerator targetPackage="arthur.dy.lee.dao" targetProject="src/main/java" type="XMLMAPPER" /> <!-- 想要生成的資料庫表,自動化工具會根據該表的結構生成相應的vo物件 --> <!-- <table schema="" tableName="t_activity_log" domainObjectName="ActivityLog"></table> <table schema="" tableName="sys_`tree" domainObjectName="SysTree"></table> --> <table schema="" tableName="finance" domainObjectName="Finance"> <!--<generatedKey column="id" sqlStatement="JDBC"/>--> </table> <!--<table schema="" tableName="finance_tree" domainObjectName="FinanceTree"></table>--> </context> </generatorConfiguration>

原始碼:

package org.mybatis.generator.internal;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.internal.util.StringUtility;

/**
 * The Class DefaultCommentGenerator.
 *
 */
public class DefaultCommentGenerator implements CommentGenerator {

    /** The properties. */
    private Properties properties;

    /** The suppress date. */
    private boolean suppressDate;

    /** The suppress all comments. */
    private boolean suppressAllComments;

    /** The addition of table remark's comments.
     * If suppressAllComments is true, this option is ignored*/
    private boolean addRemarkComments;

    private SimpleDateFormat dateFormat;

    /**
     * Instantiates a new default comment generator.
     */
    public DefaultCommentGenerator() {
        super();
        properties = new Properties();
        suppressDate = false;
        suppressAllComments = false;
        addRemarkComments = false;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addJavaFileComment(org.mybatis.generator.api.dom.java.CompilationUnit)
     */
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // add no file level comments by default
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and when it was generated.
     *
     * @param xmlElement
     *            the xml element
     */
    public void addComment(XmlElement xmlElement) {
        if (suppressAllComments) {
            return;
        }

        xmlElement.addElement(new TextElement("<!--          -->")); //$NON-NLS-1$

       /* StringBuilder sb = new StringBuilder();
        sb.append("  WARNING - "); 
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        xmlElement.addElement(new TextElement(sb.toString()));
        xmlElement
                .addElement(new TextElement(
                        "  1This element is automatically generated by MyBatis Generator, do not modify.")); 

        String s = getDateString();
        if (s != null) {
            sb.setLength(0);
            sb.append("  This element was generated on "); //$NON-NLS-1$
            sb.append(s);
            sb.append('.');
            xmlElement.addElement(new TextElement(sb.toString()));
        }*/

        //xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addRootComment(org.mybatis.generator.api.dom.xml.XmlElement)
     */
    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addConfigurationProperties(java.util.Properties)
     */
    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));

        suppressAllComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));

        addRemarkComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));

        String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT);
        if (StringUtility.stringHasValue(dateFormatString)) {
            //dateFormat = new SimpleDateFormat(dateFormatString);
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do not wish to include the Javadoc tag -
     * however, if you do not include the Javadoc tag then the Java merge capability of the eclipse plugin will break.
     *
     * @param javaElement
     *            the java element
     * @param markAsDoNotDelete
     *            the mark as do not delete
     */
    protected void addJavadocTag(JavaElement javaElement,
            boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *"); //$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        sb.append(" * "); //$NON-NLS-1$
        //sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge"); //$NON-NLS-1$
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     * 
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        if (suppressDate) {
            return null;
        } else if (dateFormat != null) {
            return dateFormat.format(new Date());
        } else {
            return new Date().toString();
        }
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable)
     */
    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
        innerClass.addJavaDocLine("/** " +introspectedTable.getFullyQualifiedTable()+" **/"); //$NON-NLS-1$
//        /*innerClass
//                .addJavaDocLine(" * 2This class was generated by MyBatis Generator."); 
//
//        sb.append(" * This class corresponds to the database table "); */
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        innerClass.addJavaDocLine(sb.toString());
//
//        addJavadocTag(innerClass, false);
//
//        innerClass.addJavaDocLine(" **/"); //$NON-NLS-1$
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addTopLevelClassComment(org.mybatis.generator.api.dom.java.TopLevelClass, org.mybatis.generator.api.IntrospectedTable)
     */
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments  || !addRemarkComments) {
            return;
        }

        //StringBuilder sb = new StringBuilder();

        topLevelClass.addJavaDocLine("/**lee20160923a "+ introspectedTable.getFullyQualifiedTable()); //$NON-NLS-1$

        String remarks = introspectedTable.getRemarks();
        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
            //topLevelClass.addJavaDocLine(" * 3Database Table Remarks:");
            String[] remarkLines = remarks.split(System.getProperty("line.separator"));  //$NON-NLS-1$
            for (String remarkLine : remarkLines) {
                topLevelClass.addJavaDocLine(" *   lee20160923b" + remarkLine);  //$NON-NLS-1$
            }
        }
       /* topLevelClass.addJavaDocLine(" *"); //$NON-NLS-1$

        topLevelClass.addJavaDocLine(" * "); //$NON-NLS-1$

        sb.append(introspectedTable.getFullyQualifiedTable());
        topLevelClass.addJavaDocLine(sb.toString());

        addJavadocTag(topLevelClass, true);*/

        topLevelClass.addJavaDocLine(" */"); //$NON-NLS-1$
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addEnumComment(org.mybatis.generator.api.dom.java.InnerEnum, org.mybatis.generator.api.IntrospectedTable)
     */
    public void addEnumComment(InnerEnum innerEnum,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
//        innerEnum.addJavaDocLine("/**"); //$NON-NLS-1$
//        innerEnum
//                .addJavaDocLine(" * 51This enum was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * 52This enum corresponds to the database table "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        innerEnum.addJavaDocLine(sb.toString());
//
//        addJavadocTag(innerEnum, false);
//
//        innerEnum.addJavaDocLine(" */"); //$NON-NLS-1$
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
     */
    public void addFieldComment(Field field,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        String remarks = introspectedColumn.getRemarks()+"  "+ introspectedColumn.getActualColumnName();
        field.addJavaDocLine("/** "+remarks+ " **/");
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable)
     */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
        field.addJavaDocLine("/**   tableName: "+introspectedTable.getFullyQualifiedTable()+"   **/"); 
//        field.addJavaDocLine(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()); //$NON-NLS-1$
//
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        field.addJavaDocLine(sb.toString());
//
//        addJavadocTag(field, false);
//
//        field.addJavaDocLine(" */"); //$NON-NLS-1$
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addGeneralMethodComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable)
     */
    public void addGeneralMethodComment(Method method,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
//        method.addJavaDocLine("/**"); //$NON-NLS-1$
//        method
//                .addJavaDocLine(" * 7This method was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * 72This method corresponds to the database table "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        method.addJavaDocLine(sb.toString());
//
//        addJavadocTag(method, false);
//
//        method.addJavaDocLine(" */"); //$NON-NLS-1$

    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addGetterComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
     */
    public void addGetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**   "+introspectedColumn.getRemarks()+"  "+ introspectedColumn.getActualColumnName() +"   **/");
    }

    public void addSetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**   "+introspectedColumn.getRemarks()+"  "+ introspectedColumn.getActualColumnName() +"   **/");
    }

    /* (non-Javadoc)
     * @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable, boolean)
     */
    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
        innerClass.addJavaDocLine("/**  tableName: "+introspectedTable.getFullyQualifiedTable()+"   **/"); //$NON-NLS-1$
//        innerClass
//                .addJavaDocLine(" * 8This class was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * 82This class corresponds to the database table "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        innerClass.addJavaDocLine(sb.toString());
//
//        addJavadocTag(innerClass, markAsDoNotDelete);
//
//        innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
    }
}

分頁

在generatorConfig.xml中加入:

<plugin type="org.mybatis.generator.plugins.MySQLPaginationPlugin"></plugin>

分頁原始碼

下載mybaits-generator源下載,然後在org.mybatis.generator.plugins路徑下新建一下類:MySQLPaginationPlugin
然後編輯後放到eclipse->plugin下的 org.mybatis.generator.core_1.3.4.201608190045.jar包裡即可。
這樣做的好處是,如果你自己寫的話,你需要打成jar包,然後再在本地倉庫引用,比較麻煩,否則你會拋無法例項化物件的錯誤。錯誤如下所示:

D:\Workspaces_All\2016.08.13-neon-springmvc\.metadata\.plugins\org.mybatis.generator.eclipse.ui\.generatedAntScripts\springmvc-generatorConfig.xml.xml:4: java.lang.RuntimeException: Cannot instantiate object of type org.mybatis.generator.plugins.MySQLPaginationPlugin 
java.lang.RuntimeException: Cannot instantiate object of type org.mybatis.generator.plugins.MySQLPaginationPlugin 

自已寫的 MySQLPaginationPlugin.class類

package org.mybatis.generator.plugins;

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.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

public class MySQLPaginationPlugin extends PluginAdapter {

    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        // add field, getter, setter for limit clause
        addLimit(topLevelClass, introspectedTable, "offset");
        addLimit(topLevelClass, introspectedTable, "limit");
        return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
            IntrospectedTable introspectedTable) {
        XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$
        isNotNullElement.addAttribute(new Attribute("test", "offset != null and offset >= 0 and limit != null and limit>=0")); //$NON-NLS-1$ //$NON-NLS-2$
        isNotNullElement.addElement(new TextElement("limit ${offset} , ${limit}"));

        element.addElement(isNotNullElement);
        return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
    }

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

    @Override
    public boolean validate(List<String> arg0) {
        return true;
    }

}

如果不用分頁物件,只是用offset和limit屬性的話,下面的就不用看了。如果分頁是用物件的話, 用這個: MySQLPagerPlugin

package org.mybatis.generator.plugins;

import org.mybatis.generator.api.CommentGenerator;
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.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.List;

public class MySQLPagerPlugin extends PluginAdapter {
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
                                              IntrospectedTable introspectedTable) {

        addPage(topLevelClass, introspectedTable, "page");
        return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
                                                                     IntrospectedTable introspectedTable) {
        XmlElement page = new XmlElement("if");
        page.addAttribute(new Attribute("test", "page != null"));
        page.addElement(new TextElement("limit #{page.begin} , #{page.length}"));
        element.addElement(page);

        return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
    }

    /**
     * @param topLevelClass
     * @param introspectedTable
     * @param name
     */
    private void addPage(TopLevelClass topLevelClass, IntrospectedTable introspectedTable,
                         String name) {
        topLevelClass.addImportedType(new FullyQualifiedJavaType(
                "com.aliyun.activity.dal.model.Page"));
        CommentGenerator commentGenerator = context.getCommentGenerator();
        Field field = new Field();
        field.setVisibility(JavaVisibility.PROTECTED);
        field.setType(new FullyQualifiedJavaType("com.aliyun.activity.dal.model.Page"));
        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(new FullyQualifiedJavaType(
                "com.aliyun.activity.dal.model.Page"), name));
        method.addBodyLine("this." + name + "=" + name + ";");
        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        topLevelClass.addMethod(method);
        method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(new FullyQualifiedJavaType("com.aliyun.babel.model.Page"));
        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;
    }
}

生成的效果程式碼

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

如果使用page物件進行分頁,需要加入page類

import java.io.Serializable;

public final class Page implements Serializable {

    /**
     * 預設的序列化版本 id.
     */
    private static final long serialVersionUID = 1L;
    /**
     * 分頁查詢開始記錄位置.
     */
    private int begin;
    /**
     * 分頁檢視下結束位置.
     */
    private int end;
    /**
     * 每頁顯示記錄數.
     */
    private int length = 20;
    /**
     * 查詢結果總記錄數.
     */
    private int totalRecords;
    /**
     * 當前頁碼.
     */
    private int pageNo;
    /**
     * 總共頁數.
     */
    private int pageCount;

    public Page() {
    }

    /**
     * 建構函式.
     *
     * @param begin
     * @param length
     */
    public Page(int begin, int length) {
        this.begin = begin;
        this.length = length;
        this.end = this.begin + this.length;
        this.pageNo = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
    }

    /**
     * @param begin
     * @param length
     * @param count
     */
    public Page(int begin, int length, int totalRecords) {
        this(begin, length);
        this.totalRecords = totalRecords;
    }

    /**
     * 設定頁數,自動計算資料範圍.
     *
     */
    public Page(int pageNo) {
        this.pageNo = pageNo;
        pageNo = pageNo > 0 ? pageNo : 1;
        this.begin = this.length * (pageNo - 1);
        this.end = this.length * pageNo;
    }

    public int getBegin() {
        return begin;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    public void setBegin(int begin) {
        this.begin = begin;
        if (this.length != 0) {
            this.pageNo = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
        }
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
        if (this.begin != 0) {
            this.pageNo = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
        }
    }

    public int getTotalRecords() {
        return totalRecords;
    }

    public void setTotalRecords(int totalRecords) {
        this.totalRecords = totalRecords;
        this.pageCount = (int) Math.floor((this.totalRecords * 1.0d) / this.length);
        if (this.totalRecords % this.length != 0) {
            this.pageCount++;
        }
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
        pageNo = pageNo > 0 ? pageNo : 1;
        this.begin = this.length * (pageNo - 1);
        this.end = this.length * pageNo;
    }

    public int getPageCount() {
        if (pageCount == 0) {
            return 1;
        }
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder("begin=").append(begin).append(", end=")
                .append(end).append(", length=").append(length).append(", totalRecords=").append(
                        totalRecords).append(", pageNo=").append(pageNo).append(", pageCount=")
                .append(pageCount);
        return builder.toString();
    }
}

idea

pom.xml 中配置build

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.4</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.34</version>
                    </dependency>
                    <!--<dependency>
                        <groupId>com.xxg</groupId>
                        <artifactId>mybatis-generator-plugin</artifactId>
                        <version>1.0.0</version>
                    </dependency>-->
                </dependencies>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

覆蓋jar

用上面csdn資源上下載的 mybatis-generator-core-1.3.4.jar
覆蓋 C:\Users\Administrator.m2\repository\org\mybatis\generator\mybatis-generator-core\1.3.4\mybatis-generator-core-1.3.4.jar (如果是用的idea預設的maven的話)

執行

這裡寫圖片描述

轉載請註明出處:

相關推薦

mybaits-generator生成中文註釋

mybaits-generator修改的版本:1.3.4 org.mybatis.generator.core_1.3.4.201608190045.jar 修改原始碼路徑: org.mybatis.generator.internal.Default

mybatis generator 生成中文註釋

org stringbu pda actual dset jdb after format) element mybatis generator默認生成 的註釋太奇葩了,完全不能拿到生產去用,不過幸虧提供了接口可以自己擴展。長話短說,要生成如下的domain, pack

myBatis-generator 生成中文註釋的問題

mybatis.generator的官方外掛只能生成一些無用的英文註釋,要生成中文註釋需要修改原始碼。 現在以mybatis.generator-1.3.5為例,說明修改原始碼的內容。 修改的內容一共兩個類:DefaultCommentGenerator.java和 MyB

Mybatis Generator的model生成中文註釋,支持oracle和mysql(通過實現CommentGenerator接口的方法來實現)

req gre files Language default dom sel setter ini 在看本篇之前,最好先看一下上一篇通過實現CommentGenerator接口的方法來實現中文註釋的例子,因為很多操作和上一篇基本是一致的,所以本篇可能不那麽詳細. 首先說一

mybatis 根據 資料庫表 自動生成 實體 自動生成中文註釋

原文地址:https://www.cnblogs.com/NieXiaoHui/p/6094144.html (將原文copy到此處,怕原作者刪除,順便記錄實際操作中我遇到的問題) 原文: 專案裡新建表時model,mapper以及mapper.xml基本都是用Myba

Mybatis Generator的model生成中文註釋

在看本篇之前,最好先看一下上一篇通過實現CommentGenerator介面的方法來實現中文註釋的例子,因為很多操作和上一篇基本是一致的,所以本篇可能不那麼詳細.首先說一下上篇通過實現CommentGenerator介面的一些不足,畢竟只是實現了CommentGenerato

Mybatis Generator的model生成中文註釋,支援oracle和mysql(通過修改原始碼的方式來實現)

在看本篇之前,最好先看一下上一篇通過實現CommentGenerator介面的方法來實現中文註釋的例子,因為很多操作和上一篇基本是一致的,所以本篇可能不那麼詳細. 首先說一下上篇通過實現CommentGenerator介面的一些不足,畢竟只是實現了CommentGenerator介面,在裡面的方法再怎麼改,

微信小程式生成列表功能 Thinkphp後臺呼叫資料庫

首先需要在app.json的window選項中或頁面配置中開啟enablePullDownRefresh "enablePullDownRefresh": true wxml頁面:  <view class="page-header"> <text c

Mybatis-利用Mybatis Generator外掛生成基於資料庫方言的語句,統計記錄總數

眾所周知,Mybatis本身沒有提供基於資料庫方言的分頁功能,而是基於JDBC的遊標分頁,很容易出現效能問題。網上有很多分頁的解決方案,不外乎是基於Mybatis本機的外掛機制,通過攔截Sql做分頁。但是在像Oracle這樣的資料庫上,攔截器生成的Sql語句沒有變數繫

hibernate(jpa)根據實體動態生成查詢條件,實現問題的解決方案

hibernate如何根據傳進去實體的不為空屬性生成動態查詢,並實現分頁,經過檢視hibernate api需要用到Criteria ,但是Criteria 有個缺點就是當另一個表A中某一外來鍵列是該表B的主鍵,如果A表中有兩條記錄對應B表的某一主鍵,則查詢結果中B表的該記錄

mybatis generator 生成資料庫註釋DAO原始碼

重寫一個註釋類 打包 安裝到maven 設定pom generatorConfig 生成原始碼 mybatis-generator:generate 寫一個 MyCommentGenerator 類繼承 DefaultCommentGenerator 重

mybatis generator 生成資料庫註釋等問題

mybatis程式碼生成器生成資料庫的註釋,找了半天沒有找到非常詳細可用的,於是我打算自己整理一份,分享出來,以下是本人親身經歷的問題處理流程,實踐有效。 前提:可以使用一般的mybatis generator 程式碼生成器 及配置各種基本註解,這些不是本文重點,不再過多敘

Django自

per ews eat tor pla ont models obj pre urls.py 1 from django.conf.urls import url 2 from django.contrib import admin 3 from app01 imp

thinkphp自

thinkphp 自帶 分頁類 thinkphp自帶分頁使用案例:$Data = M(‘Data‘); // 實例化Data數據對象 date 是你的表名 import(‘ORG.Util.Page‘);// 導入分頁類 $count = $Data->where($map

html模板生成靜態頁面及模板處理

htm 系統 測試 頻道 arr writable 屬性 處理 ges 它只讓你修改頁面的某一部分,當然這“某一部分”是由你來確定的。美工先做好一個頁面,然後我們把這個頁面當作模板(要註意的是這個模板就沒必要使用EditRegion3這樣的代碼了,這

的sql語句

ges color num order spa from col 當前 size SELECT TOP {0} * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY UpdatedDate desc) AS RowNumber,* FROM

python---django中自類使用

1.基礎使用: 後臺資料獲取: from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage#錯誤判斷 List_info = [] for i in range(1000): List_info.

TP5 自搜尋功能實現

HTML部分: <form class="layui-form" > <div class="layui-form-item"> <label class="la

SpringBoot整合MybatisPlus實現查詢

首先https://start.spring.io/下載一個springBoot的demo。   然後增加pomyila依賴,引入以下pom,除了MybatisPlus其他自己分配 <?xml version="1.0" encoding="UTF-8"?> <

mybatis增刪改查sql,,新增可以返回id

** mybatis增刪改查sql,帶分頁,新增可以返回id <resultMap type="com.spring.pojo.T_Form" id="T_FormMap"> <result column="formId" property="formId"/