A Brief Introduction to Mybatis generator Generation Tool

Keywords: PHP Mybatis MySQL Java xml

Mybatis generator

Its main function is to create Dao, entry and xml conveniently and quickly, which speeds up the development speed, and to configure OK according to the rules it provides.

There is also an important development scenario. During the development process, there must be a lot of operations on the database, such as adding new fields or something. You just delete the original set of automatically generated code and regenerate it into a new one. This is a perfect solution, but the premise is that you have to do so without the generated code. Change, just use. You don't need to change code everywhere as you develop and write code manually, and you're worried about the omissions.

In fact, there are various ways to achieve this. It's quite common to write one.

Major processes

Step 1: Adding dependencies

jdbc and generator

<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

Step 2: Configure generatorConfig.xml

This document is mainly about the description of where to come from and where to go, as well as the configuration of some special requirements.

<?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="DB2Tables" targetRuntime="MyBatis3">
        <!-- generate mysql Paginated sql The plug-in can be written by itself.-->
        <plugin type="generator.MysqlPaginationPlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <!-- Custom Annotation Rules, Inheritance DefaultCommentGenerator Rewrite some methods -->
        <commentGenerator type="generator.NewbatisGenerator">
            <!-- Whether to remove the annotation of the auto-generated date true: Yes: false:no -->
            <property name="suppressDate" value="true"/>
            <!-- Whether to remove all automatically generated comments true: Yes: false:no -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://Database Address“
                        userId="username"
                        password="password">
        </jdbcConnection>
        <!--generate entity Class Storage Location-->
        <javaModelGenerator targetPackage="Name of package( com.generator.test.entity)" targetProject="Project address to\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--Generate mapping file storage location-->
        <sqlMapGenerator targetPackage="Name of package( com.generator.test.mapper)" targetProject="Project address to\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--generate Dao Class Storage Location-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="Name of package( com.generator.test.dao)"
                             targetProject="Project address to\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table tableName="Table name" domainObjectName="The class name of the generated entity">
        </table>
    </context>
</generatorConfiguration>

  

 

Step 3: Mainly depend on your personal needs. If you don't have any requirements for annotations, pagination, etc., you can rewrite several ways to transform them.

Major examples

Amendments to annotations Newbatis Generator

public class NewbatisGenerator extends DefaultCommentGenerator {
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

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

    /**
     * Annotations to classes
     * @param topLevelClass
     * @param introspectedTable
     */
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine(" * This is the Model Class automatically generated by MyBatis Generator.“);

        StringBuilder sb = new StringBuilder();
        sb.append(" * The corresponding data table is:“);
        sb.append(introspectedTable.getFullyQualifiedTable());
        topLevelClass.addJavaDocLine(sb.toString());

        String tableRemarks = introspectedTable.getRemarks();
        if (!StringUtils.isEmpty(tableRemarks)) {
            sb.setLength(0);
            sb.append(" * Data sheet annotations:_____________“);
            sb.append(tableRemarks);
            topLevelClass.addJavaDocLine(sb.toString());
        }

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

        String curDateString = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
        sb.setLength(0);
        sb.append(" * @date ");
        sb.append(curDateString);
        topLevelClass.addJavaDocLine(sb.toString());

        topLevelClass.addJavaDocLine(" */");
    }

    /**
     * Chinese Annotations for Generated Entities Adding Fields
     */
    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().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

}

Paging Addition Mysql Pagination Plugin Automatically Generates Paging Plugin

public class MysqlPaginationPlugin extends PluginAdapter {
    public MysqlPaginationPlugin() {}

    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) {
        this.addLimit(topLevelClass, introspectedTable, "limitStart");
        this.addLimit(topLevelClass, introspectedTable, "limitSize");
        return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
    }

    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
            IntrospectedTable introspectedTable) {
        XmlElement isNotNullElement = new XmlElement("if");
        isNotNullElement
                .addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
        isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
        element.addElement(isNotNullElement);
        return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
    }

    public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,
            IntrospectedTable introspectedTable) {
        XmlElement isNotNullElement = new XmlElement("if");
        isNotNullElement
                .addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
        isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
        element.addElement(isNotNullElement);
        return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
    }

    private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable,
            String name) {
        CommentGenerator commentGenerator = this.context.getCommentGenerator();
        Field field = new Field();
        field.setVisibility(JavaVisibility.PROTECTED);
        field.setType(PrimitiveTypeWrapper.getIntegerInstance());
        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(PrimitiveTypeWrapper.getIntegerInstance(), name));
        StringBuilder sb = new StringBuilder();
        sb.append("this.");
        sb.append(name);
        sb.append(" = ");
        sb.append(name);
        sb.append(";");
        method.addBodyLine(sb.toString());
        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        topLevelClass.addMethod(method);
        Method getterMethod = AbstractJavaGenerator.getGetter(field);
        commentGenerator.addGeneralMethodComment(getterMethod, introspectedTable);
        topLevelClass.addMethod(getterMethod);
    }

    public boolean validate(List<String> warnings) {
        return true;
    }



    /**
     * Generate mapper.xml, and the file content will be emptied and rewritten
     * */
    @Override
    public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
        sqlMap.setMergeable(false);
        return super.sqlMapGenerated(sqlMap, introspectedTable);
    }

}

Last step: Run Generation

There are all these official websites.

public class Generator {

    public static void main(String[] args) throws Exception{
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

    }
}

It's simple and clear, personalized and worth recommending.

Reproduced from: https://www.cnblogs.com/zhouguanglin/p/11239583.html

Posted by helpmeplease2 on Wed, 24 Jul 2019 02:45:57 -0700