A: the preface

Two: code use

<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>
<dependency>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-core</artifactId>
	<version>1.3.5</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.28</version>
</dependency>
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.2.3</version>
</dependency>

Copy the code

Write log4j configuration files

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

Copy the code

Compile the generatorconfig. XML configuration file for reverse engineering. The configuration file has too many parameters

Liverpoolfc.tv: mybatis.org/generator/c…

<?xml version="1.0" encoding="UTF-8"? >

      

<generatorConfiguration>

    <! -- Configure database information -->
    <context id="DB2Tables" targetRuntime="MyBatis3">

        <! -- Avoid generating duplicate code for plug-ins -->
        <plugin type="com.util.OverIsMergeablePlugin" />

        <! -- Whether to display comments in code -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <! -- Database connection information: driver class, connection address, user name, password, add "useSSL=false" because I have an SSL connection error -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/day23" userId="root" password="root">
        </jdbcConnection>

        <! -- Default false to parse JDBC DECIMAL and NUMERIC types to Integer, or true to parse JDBC DECIMAL and NUMERIC types to java.math.bigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <! Javabeans -->
        <javaModelGenerator targetPackage="com.pojo" targetProject="src/main/java">
            <! EnableSubPackages: enable schema as package suffix -->
            <property name="enableSubPackages" value="true" />
            <! -- whitespace before and after the value returned from the database is cleaned -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <! SQL > create SQL mapping file
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <! Create dao interface, mapper interface -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        
        <! -- Select a table to generate related files, can have one or more tables, must have table elements select a table to generate the following files: 1, SQL map file 2, generate a primary key class; 3, classes for fields other than BLOB and primary key; 4. class containing BLOB; 5, a conditional class (selectByExample, deleteByExample) for user-generated dynamic queries, optional; 6. Mapper interface (optional) tableName (required) : the tableName of the object to be generated; Note: Case sensitive. In normal cases, MBG will automatically recognize the case sensitivity of database identifiers. In general, MBG will query data tables based on the schema, catalog, or tablename, as follows: 1. If there are Spaces in schema, Catalog, or tablename, use the specified case format to query the specified format. Otherwise, if the database identifier is in uppercase, MBG will automatically change the table name to uppercase. Otherwise, if the database identifier is lowercase, MBG will automatically change the table name to lowercase and then look it up. 4, otherwise, use the specified case format to query; In addition, if the database object is case-sensitive when creating a table, even if the database identifier is uppercase, the table name will be created with the given case; In this case, set delimitIdentifiers="true" to preserve case formatting; Optional: 1. Schema: indicates the schema of the database. 2, Catalog: database catalog; Alias_actualColumnName 4, domainObjectName: alias_actualColumnName 4, domainObjectName The name of the generated domain class. If this is not set, use the table name as the name of the domain class. Somepck. DomainName = somepck. EnableInsert (default true) : specifies whether to generate an INSERT statement. EnableSelectByPrimaryKey (default true) : specifies whether to generate a statement to query objects by primary key (getById or GET). 7, enableSelectByExample (default true) : MyBatis3Simple is false, specify whether to generate dynamic query statement; EnableUpdateByPrimaryKey (default true) : specifies whether to generate a statement to modify the object according to the primary key (update). EnableDeleteByPrimaryKey (default true) : specifies whether to generate a statement to delete objects by primary key (delete). EnableDeleteByExample (default true) : MyBatis3Simple is false. EnableCountByExample (default true) : MyBatis3Simple is false. EnableUpdateByExample (default true) : MyBatis3Simple is false, which specifies whether to generate dynamic modification statements (modify only non-null attributes of the object); ModelType: reference defaultModelType of the context element, equivalent to overwriting; 14, delimitIdentifiers: See tableName for an explanation. Note that the default delimitIdentifiers are double quotes, whereas if a database like MYSQL uses' (backquotes, You also need to set the beginningDelimiter and endingDelimiter properties of the context.) 15, delimitAllColumns: Set whether all column names in the generated SQL are caused by identifiers. Note that many of the arguments in table are overwrites of the default attributes of javaModelGenerator, Context, etc. -->

        <! -- Specify the database table -->
        <table tableName="province" domainObjectName="Province" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true"
               selectByExampleQueryId="false">
            <property name="my.isgen.usekeys" value="true"/>
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>
Copy the code

The reverse engineering tool has a Bug that every time you re-run the code to generate POJOs, SQL mapping files, and Mapper interfaces it does not overwrite the original and causes duplication, so a plug-in was written to use reflection to solve the problem

package com.util;

import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import java.lang.reflect.Field;
import java.util.List;

/ * * *@author admin
 * @version 1.0.0
 * @ClassName OverIsMergeablePlugin.java
 * @DescriptionTODO fixes Mybatis reverse engineering file not overwriting issue *@createTime2020 02 06 12:37:00 */
public class OverIsMergeablePlugin extends PluginAdapter {

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

    @Override
    public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
        try {
            Field field = sqlMap.getClass().getDeclaredField("isMergeable");
            field.setAccessible(true);
            field.setBoolean(sqlMap, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true; }}Copy the code

Write a running class that is not normally allowed to run. Add a time limit to prevent accidental running of the class from overwriting comments on the original POJO class, mapper interface, and XML mapping file.

public class MybatisGenerator {

    public static void main(String[] args) throws Exception {
        String today = "2020-02-06";

        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        Date now =sdf.parse(today);
        Date d = new Date();

        if(d.getTime()>now.getTime()+1000*60*60*24){
            System.err.println("-- failed to run successfully --");
            System.err.println("-- failed to run successfully --");
            System.err.println("This program is destructive and should only be run once. If it must be run again, change the today variable to today, as in :" + sdf.format(new Date()));
            return;
        }

        if(false)
            return;
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        InputStream is= MybatisGenerator.class.getClassLoader().getResource("generatorConfig.xml").openStream();
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

        System.out.println("Generated code successfully, can only be executed once, subsequent execution will overwrite changes made on mapper, POJO, XML, etc."); }}Copy the code

Three: related links

Mybatis reverse engineering configuration details: blog.csdn.net/xlx1992/art… After reverse engineering to generate the mapper interfaces using blog.csdn.net/biandous/ar…