MybatisGenerator extension: Custom comment generator

Posted by trrobnett on Mon, 25 Nov 2019 20:57:54 +0100

MybatisGenerator extension: Custom comment generator

I believe you have a certain understanding of the mybatisgenerator. I love and hate it. The code generated by the mybatisgenerator plug-in will generate comments, which are all useless to us. Although it can prevent the generation of comments, it is not good to have no comments, but the mybatisgenerator plug-in provides a custom comment generator. Let's write a comment according to the field To generate field comments and custom class comments

1. First write a custom comment generator and inherit the CommentGenerator interface

package javaDIYFree.generator;

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.*;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.internal.util.StringUtility;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

/**
 * @author Hearts
 * @date 2019/4/16
 * @desc
 */
public class SimpleCommentGenerator implements CommentGenerator {

    private boolean suppressDate = false;
    private boolean suppressAllComments = false;
    private boolean addRemarkComments = false;
    private SimpleDateFormat dateFormat;
    private StringBuffer classCommentBanner;
    private String delimiter = "\n";


    //We can observe and learn from the official default default comment generator and write our own comment generator
    public void addConfigurationProperties(Properties properties) {

        //Initialize classCommentBanner
        classCommentBanner = new StringBuffer();

        //Gets whether to block the generation of time comments. The default is true
        suppressDate = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
        //Gets whether to block all comments from being generated
        suppressAllComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
        //Get whether to generate comments
        addRemarkComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));
        //Custom field, the delimiter of the comment can be customized by configuring the delimiter property in xml
        if (properties.getProperty("delimiter") != null){
            delimiter = properties.getProperty("delimiter");
        }

        //Get time formatted string
        String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT);
        if (StringUtility.stringHasValue(dateFormatString)) {
            dateFormat = new SimpleDateFormat(dateFormatString);
        }

        //Get custom class comment banner
        if (properties.getProperty("classCommentBanner") != null){
            String baseClassCommentBanner = properties.getProperty("classCommentBanner");
            //Replace the ${date} string with the current format time
            baseClassCommentBanner = baseClassCommentBanner.replace("${date}",getDateString());
            classCommentBanner.append(baseClassCommentBanner);
        }

    }

    /**
     * Get format time
     * @return
     */
    private String getDateString(){
        if (suppressDate) {
            return null;
        } else if (dateFormat != null) {
            return dateFormat.format(new Date());
        } else {
            return new Date().toString();
        }
    }

    /**
     * Add field comment
     * @param field
     * @param introspectedTable
     * @param introspectedColumn
     */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        generatorComment(introspectedColumn.getRemarks(),field);
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
    }

    /**
     * Add entity class comment
     * @param topLevelClass
     * @param introspectedTable
     */
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        classCommentBanner.append(introspectedTable.getRemarks());
        generatorComment(classCommentBanner.toString(),topLevelClass);
    }

    /**
     * Add inner class comment
     * @param innerClass
     * @param introspectedTable
     */
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {

    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) {
    }

    /**
     * Add enumeration comment
     * @param innerEnum
     * @param introspectedTable
     */
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {

    }

    /**
     * Add getter method comment
     * @param method
     * @param introspectedTable
     * @param introspectedColumn
     */
    public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    /**
     * Add a setter method comment
     * @param method
     * @param introspectedTable
     * @param introspectedColumn
     */
    public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    /**
     * Add common method comment
     * @param method
     * @param introspectedTable
     */
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {

    }

    /**
     * Add java file comment
     * @param compilationUnit
     */
    public void addJavaFileComment(CompilationUnit compilationUnit) {
    }

    /**
     * Add mapper.xml comment
     * @param xmlElement
     */
    public void addComment(XmlElement xmlElement) {

    }

    public void addRootComment(XmlElement xmlElement) {

    }


    /**
     * Generate comment comment
     * @param remark
     * @param field
     */
    private void generatorComment(String remark,JavaElement field) {
        //If generating comments is blocked
        if (suppressAllComments){
            return;
        }

        final boolean validRemark = StringUtility.stringHasValue(remark);
        //Judge whether to add notes according to parameters and notes
        if (validRemark && addRemarkComments){
            final String[] remarkLine = remark.split(delimiter);

            //Commentary
            field.addJavaDocLine("/**");

            for (String s : remarkLine) {

                field.addJavaDocLine(" * "+s);
            }

            //End note
            field.addJavaDocLine(" */");


        }
    }





}

2. Configure in generatorContext.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>


    <context id="Mysql" defaultModelType="flat" targetRuntime="MyBatis3Simple">


        <!--Set separator automatically-->
        <!--<property name="autoDelimitKeywords" value="true"/>-->
        <!-- Set separator manually -->
        <property name="autoDelimitKeywords" value="true"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>


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

        <!--Set to use java Character encoding of documents-->
        <!--<property name="javaFileEncoding" value="UTF-8"/>-->

        <!--
        Annotation generation label
        type attribute:No need to write by default. If you don't write, you will use the default annotation generator, custom extension, and fill in the fully qualified class name of the custom class
        -->
        <commentGenerator type="javaDIYFree.generator.SimpleCommentGenerator">
            <!--Prevent comments from being generated, default is false-->
            <property name="suppressAllComments" value="false"/>
            <!--Prevent generated comments from including timestamps,Default is false-->
            <!--<property name="suppressDate" value="true"/>-->
            <property name="dateFormat" value="yyyy-MM-dd"/>
            <!--Whether to add notes to the table? The default value is false-->
            <property name="addRemarkComments" value="true"/>
            <!--Set custom class banner comments-->
            <property name="classCommentBanner" value="@author: hearts,@date: ${date},@desc: "/>
            <!--Comma separated custom comments-->
            <property name="delimiter" value=","/>
        </commentGenerator>


        <!--jdbc Connect-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test"
                        userId="root"
                        password="abcdef"
                        >
        </jdbcConnection>

        <!--To configure jdbc Type and java How to convert types-->
        <!--forceBigDecimals Property to control whether the DECIMAL and NUMERIC Type JDBC Field to Java Type-->
        <!--java.math . BigDecimal ,The default value is false,Generally, configuration is not required-->
        <!--<javaTypeResolver>-->
            <!--<property name="forceBigDecimals" value="false" />-->
        <!--</javaTypeResolver>-->

        <!--Control generated entity class-->
        <!--targetPackage Generate enrollment stored in entity class
        targetProject Project path to build entity class-->
        <javaModelGenerator targetPackage="javaDIYFree.model" targetProject="src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"  targetProject="src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="javaDIYFree.dao"  targetProject="src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table modelType="" tableName="user" domainObjectName="User">
        </table>
    </context>
</generatorConfiguration>

test

Run the MybatisGenerator program. If you have any questions, go to MybatisGenerator tutorial
Note: only when there is a comment on the field in the database can there be a comment on the field. I don't know why the comment on the database table can't be obtained

Project structure chart

End

If you have any comments, please discuss them together

Topics: Mybatis Java xml JDBC