Mybatis reverse generation model with Chinese annotations

mybatis can directly generate model classes and mappper files for us through database tables.

Here's how to configure it, especially how to add Chinese comments. The current premise is that the data tables and fields have Chinese comments.

For example this:

The following configuration automatically generates model classes, mapper classes and mapper xml files.

 

There are many articles on the Internet about how to use mybatis-generator to generate Java objects, so I won't go into details here. You can go to Baidu so, such as http://www.cnblogs.com/smileberry/p/4145872.html , http://www.cnblogs.com/yjmyzz/p/4210554.html

Assuming that we have designed the table structure, tables and fields have their own annotations (in fact, Chinese and English do not matter).

The following is the reverse generation process:

Create a new generatorConfig.xml in the classpath with the following configuration

<?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>
    <!--Specify the location of the jdbc driver jar package for a specific database-->
    <classPathEntry location="${jdbc.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">

        <!--jdbc database connection-->
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.connectionURL}"
                userId="${jdbc.userId}"
                password="${jdbc.password}">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="comxxx.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="constructorBased" value="true"/>
            <property name="trimStrings" value="true"/>
           <property name="immutable" value="false"/>
        </javaModelGenerator>

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

        <javaClientGenerator targetPackage="com.xxx.mapper"
                             targetProject="src/main/java"
                             type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <table tableName="import_goods_quantity"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <!--<generatedKey identity="true" sqlStatement="MySql" column="id"/>-->
        </table>
     </context>
</generatorConfiguration>

 generatorConfiguration has a subtag

<properties resource="xxx.properties"></properties>

 

Configuration variables can be introduced.

 

After configuration, you can use the plugin mybatis-generator-maven-plugin to generate it.

<plugin>
   <groupId>org.mybatis.generator</groupId>
   <artifactId>mybatis-generator-maven-plugin</artifactId>
   <version>1.3.5</version>
   <configuration>
      <verbose>true</verbose>
      <overwrite>true</overwrite>
   </configuration>
</plugin>

We are using version 1.3.5 here.


 Now use mybatis-generator:generate to generate Java classes and xml files to the specified directory.

 

The class annotations thus generated are automatic, meaningless descriptions of time, similar to

@ mbg.generated

We hope that the annotations in the database can be taken over, how to do it?

 

Create a new maven project with coordinates such as

<groupId>com.xxx</groupId>
<artifactId>comment_generator</artifactId>
<version>1.0-SNAPSHOT</version>

 import dependencies

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>

 Create a new annotation configuration class

public class MybatisCommentGenerator implements CommentGenerator {
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

    public MybatisCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    /**
     * Adds properties for this instance from any properties configured in the
     * CommentGenerator configuration.
     * <p>     * This method will be called before any of the other methods.
     *
     * @param properties All properties from the configuration
     */
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));
    }

    /**     *
     * @param field              the field
     * @param introspectedTable  the introspected table
     * @param introspectedColumn
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString());

        addJavadocTag(field, false);

        field.addJavaDocLine(" */");
    }

    /**
     * Adds the field comment.
     *
     * @param field             the field
     * @param introspectedTable
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine(" */");
    }
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        topLevelClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getRemarks());
        sb.append(" ");
        sb.append(introspectedTable.getTableType());
        sb.append(" ");
        sb.append(getDateString());
        topLevelClass.addJavaDocLine(sb.toString());
        topLevelClass.addJavaDocLine(" */");
    }

    /**
     * Adds the inner class comment.
     *
     * @param innerClass        the inner class
     * @param introspectedTable
*/
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        sb.append(" ");
        sb.append(getDateString());
        innerClass.addJavaDocLine(sb.toString());
        innerClass.addJavaDocLine(" */");
    }

    /**
     * Adds the inner class comment.
     *
     * @param innerClass        the inner class
     * @param introspectedTable the introspected table
     * @param markAsDoNotDelete
*/
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString());

        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);

        addJavadocTag(innerClass, markAsDoNotDelete);

        innerClass.addJavaDocLine(" */");
    }

    /**
     * Adds the enum comment.
     *
     * @param innerEnum the inner enum
     * @param introspectedTable
*/
public void addEnumComment (InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerEnum.addJavaDocLine("/**");
        addJavadocTag(innerEnum, false);
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString());
        innerEnum.addJavaDocLine(" */");
    }

    /**
     * Adds the getter comment.
     *
     * @param method             the method
     * @param introspectedTable  the introspected table
     * @param introspectedColumn
*/
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**");

        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        addJavadocTag(method, false);

        method.addJavaDocLine(" */");
    }

    /**
     * Adds the setter comment.
     *
     * @param method             the method
     * @param introspectedTable  the introspected table
     * @param introspectedColumn
*/
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        Parameter parm = method.getParameters().get(0);
        sb.setLength(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        addJavadocTag(method, false);

        method.addJavaDocLine(" */");
    }

    /**
     * Adds the general method comment.
     *
     * @param method            the method
     * @param introspectedTable
*/
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
//        addJavadocTag(method, false);
StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        String s = method.getName();
        sb.append(' ');
        sb.append(s);
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" */");
    }
public void addJavaFileComment(CompilationUnit compilationUnit) {

    }
public void addComment(XmlElement xmlElement) {

    }
public void addRootComment(XmlElement rootElement) {
    }

    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }
}

 Install this project. (Can be closed, unless you want to continue to modify)

 

 

Go back to the previous project that needs to be reverse generated.

In generatorConfig.xml, modify

commentGenerator

element is

<commentGenerator type="com.xxx.mybatis.MybatisCommentGenerator">
    <property name="suppressDate" value="false"/>
    <property name="suppressAllComments" value="false"/>
</commentGenerator>

 Where type points to the annotation configuration class in the project just now. suppressDate is optional according to personal preference.

Modify the generator plugin and introduce the newly created project dependencies:

<plugin>
   <groupId>org.mybatis.generator</groupId>
   <artifactId>mybatis-generator-maven-plugin</artifactId>
   <version>1.3.5</version>
   <configuration>
      <verbose>true</verbose>
      <overwrite>true</overwrite>
   </configuration>
             <dependencies>
                 <dependency>
                     <groupId>com.xxx</groupId>
                     <artifactId>comment_generator</artifactId>
                     <version>1.0-SNAPSHOT</version>
                 </dependency>
             </dependencies>
</plugin>

 Run the plugin again, and you can see that the model class has the annotations we wrote in the database.

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326226694&siteId=291194637