1. Pom dependency

  <! -- MyBatis generator -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.3</version>
</dependency>
Copy the code

2.generatorConfig.xml

Write generatorconfig. XML and generator.properties files in the SRC /resources directory


      
<! DOCTYPEgeneratorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generator.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <! Generate serialization method for model -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <! Create a toString method for the generated Java model
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <! -- You can customize the code comment to generate model -->
        <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">
            <! -- Whether to remove automatically generated comments true: yes: false: no -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <! -- Configure database connection -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <! Mysql > update mysql > update mysql > update mysql > update mysql
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <! -- Specify the path to generate the model -->
        <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="src/main/java"/>
        <! Mapper.xml -->
        <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="src/main/resources"/>
        <! -- Specify the path to generate mapper interface -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"
                             targetProject="src/main/java"/>
        <! TableName = %-->
        <table tableName="pms_brand">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
Copy the code

Of the generator. The properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/mall? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai jdbc.userId=root jdbc.password=rootCopy the code

3. Annotation class writing

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/** * Custom comment generator */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;

    /** * Sets the user configuration parameters */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /** * Add comment to field */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        // Determine whether to add remarks based on the parameters and remarks
        if(addRemarkComments && StringUtility.stringHasValue(remarks)) { addFieldJavaDoc(field, remarks); }}/** * Add comments to the fields of model */
    private void addFieldJavaDoc(Field field, String remarks) {
        // Document comment begins
        field.addJavaDocLine("/ * *");
        // Get the remarks of database fields
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for (String remarkLine : remarkLines) {
            field.addJavaDocLine("*" + remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */"); }}Copy the code

4. Start class writing

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/** * The code used to produce MBG */
public class Generator {
    public static void main(String[] args) throws Exception {
        // Warning message during MBG execution
        List<String> warnings = new ArrayList<String>();
        // If the generated code is duplicated, override the original code
        boolean overwrite = true;
        // Read our MBG configuration file
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        / / create the MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        // Execute the generated code
        myBatisGenerator.generate(null);
        // Displays a warning message
        for(String warning : warnings) { System.out.println(warning); }}}Copy the code

Reference: juejin. Cn/post / 684490…