tk-mapper code generation – working

Generating Effects

mybatis3 code generation


mybatis-generator/generatorConfig.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>
    <classPathEntry
            location="F:\software\mysql-jar\mysql-connector-java-5.1.45\mysql-connector-java-5.1.45-bin.jar" />
    <context id="context1" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- Whether to remove automatically generated comments true: yes: false: no -->
            <property name="suppressAllComments" value="true" />
            <!--Database connection information: driver class, connection address, user name, password -->
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/ht-oa?useSSL=false" userId="root" password="123456">
        </jdbcConnection>
        <javaModelGenerator targetPackage="com.liuyang.domain"
                            targetProject="src/main/java" />
        <sqlMapGenerator targetPackage="sqlmapper"
                         targetProject="src/main/resources" />
        <javaClientGenerator targetPackage="com.liuyang.repository"
                             targetProject="src/main/java" type="XMLMAPPER" />
        <!-- shema database tableName indicates -->
        <table schema="oa_product" tableName="staff" />
        <table schema="hjy_pom" tableName="benefits_formula" />
        <table schema="hjy_pom" tableName="benefits_share" />
        <table schema="hjy_pom" tableName="business_tree" />
        <table schema="hjy_pom" tableName="company" />
        <table schema="hjy_pom" tableName="dictionary_type" />
        <table schema="hjy_pom" tableName="dictionary_data" />
        <table schema="hjy_pom" tableName="entrust_company" />
        <table schema="hjy_pom" tableName="entrust_contract" />
        <table schema="hjy_pom" tableName="entrust_contract_company_ref" />
        <table schema="hjy_pom" tableName="entrust_cooperate" />
        <table schema="hjy_pom" tableName="entrust_pay" />
        <table schema="hjy_pom" tableName="flow" />
        <table schema="hjy_pom" tableName="expert" />
        <table schema="hjy_pom" tableName="flow_record" />
        <table schema="hjy_pom" tableName="invoice_record" />
        <table schema="hjy_pom" tableName="main_contract" />
        <table schema="hjy_pom" tableName="main_contract_plan" />
        <table schema="hjy_pom" tableName="mian_contract_company" />
        <table schema="hjy_pom" tableName="pay_record" />
        <table schema="hjy_pom" tableName="project" />
        <table schema="hjy_pom" tableName="receivable_record" />
        <table schema="hjy_pom" tableName="tendering_bid" />
        <table schema="hjy_pom" tableName="permission" />
        <table schema="hjy_pom" tableName="role" />
        <table schema="hjy_pom" tableName="role_permission_ref" />
        <table schema="hjy_pom" tableName="user_role" />
        <table schema="hjy_pom" tableName="user_role_ref" />
        <table schema="hjy_pom" tableName="company_people" />
        <table schema="hjy_pom" tableName="company_equipment" />
        <table schema="gza_srms" tableName="user_copy" />
    </context>
</generatorConfiguration>

Need to download the mysql driver: https://downloads.mysql.com/archives/c-j/
pom dependencies and plugins

 <build>
     <finalName>gza-srms</finalName>
        <plugins>
            <!-- Srping Boot packaging tool -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- Without this configuration, devtools will not take effect -->
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
            <!-- Specify JDK compilation version -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <!--When maven is packaged, tell maven that web.xml is not needed, otherwise it will report an error that web.xml cannot be found -->
                    <!-- <failOnMissingWebXml>false</failOnMissingWebXml> -->
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!-- The location of the generator tool configuration file -->
                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <!-- <dependency>
                              <groupId>mysql</groupId>
                              <artifactId>mysql-connector-java</artifactId>
                              <version>5.1.34</version>
                          </dependency>-->
                    <!-- <dependency>
                         <groupId>org.mybatis.generator</groupId>
                         <artifactId>mybatis-generator-core</artifactId>
                         <version>1.3.2</version>
                     </dependency>-->
                </dependencies>
            </plugin>
        </plugins>
        <!--To solve the problem that the idea cannot run through the code, this must be added, otherwise the default path cannot find the xml and resources files-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.xls</include>
                    <include>template/*.xlsx</include>
                    <include>**/*.docx</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
    
<profiles>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>uat</id>
<properties>
<activatedProperties>uat</activatedProperties>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles>

pom
Work

 <!--mybatis-plus-->

        <dependency>
            <groupId>com.hengtiansoft.sc</groupId>
            <artifactId>data-support-orm-mybatisplus</artifactId>
            <version>2.0.0-SPRING-2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.1</version>
        </dependency>

 <!--mybatis-plus-->

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.0.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

mybatis-plus

 <!--mybatis-plus-->

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.0.7.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
                <version>2.1.3.RELEASE</version>
            </dependency>

Generator

package com.hengtiansoft.userservice.generate;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;

import java.util.Collections;

/**
 * MP code generator main class
 *
 * @author Chenyang Fan
 * @since 1.0.0
 */
public class Generator {

    // project address
    private static String projectName = "/user-service";
    private static String packageName = "com.hengtiansoft";

    /**
     * filter table prefix
     */
    private static String[] tablePrefix = new String[]{

    };

    /**
     * filter table suffix
     */
    private static String[] tableSuffix = new String[]{

    };

    /**
     * filter field prefix
     */
    private static String[] fieldPrefix = new String[]{

    };

    /**
     * filter field suffix
     */
    private static String[] fieldSuffix = new String[]{

    };

    // Set the table to be mapped (if you want to use it, you need to open the comment of addInclude(tableName) in strategyConfig)
    private static String[] tableName = new String[]{
            "dictionary_type"
    };

    public static void main(String[] args) {


        String url = "jdbc:mysql://172.24.2.92:3306/ht-oa?useUnicode=true &characterEncoding=utf-8 &useSSL=false &serverTimezone=Asia/Shanghai &verifyServerCertificate =false & amp;zeroDateTimeBehavior=CONVERT_TO_NULL & amp;nullCatalogMeansCurrent=true & amp;tinyInt1isBit=false & amp;useAffectedRows=true";
        String username = "root";
        String password = "root";

        DataSourceConfig dataSourceConfig = new DataSourceConfig. Builder(url, username, password)
                .typeConvert(new MySqlTypeConvertCustom())
                .build();

        /*
          Global Configuration (GlobalConfig)
         */
        GlobalConfig globalConfig = new GlobalConfig. Builder()
                .fileOverride() //Overwrite generated files
                .disableOpenDir() //Disable opening the output directory
                .outputDir(System.getProperty("user.dir") + projectName + "/src/main/java") //Specify the output directory
                .author("sc") //author name
                .enableSwagger() //Enable swagger mode
                .dateType(DateType.TIME_PACK) //time strategy
                .commentDate("yyyy-MM-dd") //comment date
                .build();


        /*
          Package Configuration (PackageConfig)
         */
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent(packageName) //parent package name
                .moduleName("userservice") //Parent package module name
                .entity("entity.po") //Entity package name
                .service("service") //Service package name
                .serviceImpl("service.impl") //Service Impl package name
                .mapper("mapper") //Mapper package name
                .xml("mapper.xml") //Mapper XML package name
                .controller("controller") //Controller package name
                .other("other") //custom file package name
                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + projectName + "/src/main/resources/mapper")) //path configuration information
                .build();


        /*
          Template Configuration (TemplateConfig)
         */
        TemplateConfig templateConfig = new TemplateConfig. Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .mapperXml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();


        /*
          Injection Configuration (InjectionConfig)
         */
        InjectionConfig injectionConfig = new InjectionConfig. Builder()
                .beforeOutputFile((tableInfo, objectMap) -> {
                    System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                })
                .customMap(Collections.singletonMap("test", "baomidou"))
                .customFile(Collections.singletonMap("test.txt", "/templates/test.vm"))
                .build();


        /*
          Strategy Configuration (StrategyConfig)
         */
        StrategyConfig strategyConfig = new StrategyConfig. Builder()
                .enableCapitalMode() //Enable uppercase naming
                // .enableSkipView() //Enable skip view
                .disableSqlFilter() //Disable sql filtering
                // .likeTable(new LikeTable("USER"))
                .addInclude(tableName) // Set the table to be mapped
                .addTablePrefix(tablePrefix) //Add filter table prefix
                .addTableSuffix(tableSuffix) //Add filter table suffix
                .addFieldPrefix(fieldPrefix) //Add filter field prefix
                .addFieldSuffix(fieldSuffix) //Add filter field suffix
                .build();


        /* -------------------------Entity policy configuration ----------------- ----------- */
        strategyConfig = strategyConfig
                .entityBuilder()
                .disableSerialVersionUID()
// .enableChainModel()
                .enableLombok()
// .enableRemoveIsPrefix()
                .enableTableFieldAnnotation()
// .enableActiveRecord()
                .versionColumnName("version").versionPropertyName("version")
                .logicDeleteColumnName("deleted").logicDeletePropertyName("deleteFlag")
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                .addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                .addIgnoreColumns("age")
                .addTableFills(new Column("create_time", FieldFill.INSERT)) // time record changed when inserting, created is the field name of the table
                .addTableFills(new Property("update_Time", FieldFill.INSERT_UPDATE)) // The time record of the updated table field when it was last updated
                .idType(IdType.AUTO)
                .formatFileName("%sEntity")
                .build();


        /* ---------------------------- Controller Policy Configuration ----------------- ----------- */
        strategyConfig = strategyConfig
                .controllerBuilder()
                .enableRestStyle()
                .formatFileName("%sController")
                .build();

        /* ---------------------------- Mapper policy configuration ----------------- ----------- */
        strategyConfig = strategyConfig
                .mapperBuilder()
                .enableMapperAnnotation()
                .enableBaseResultMap()
                .enableBaseColumnList()
                .formatMapperFileName("%sDao")
                .formatXmlFileName("%sMapper")
// .formatXmlFileName("%sXml")
                .build();


        /* ---------------------------- service policy configuration ----------------- ----------- */
        strategyConfig = strategyConfig
                .serviceBuilder()
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImp")
                .build();

        AutoGenerator autoGenerator = new AutoGenerator(dataSourceConfig);
        autoGenerator.global(globalConfig);
        autoGenerator. packageInfo(packageConfig);
        autoGenerator. strategy(strategyConfig);
        autoGenerator. execute();


    }
}

MySqlTypeConvertCustom

package com.hengtiansoft.userservice.generate;

import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.ITypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;

/**
 * Description: tinyint(1) is mapped to integer
 *
 * @author wenlongchen
 * @since 2022/6/13
 */
public class MySqlTypeConvertCustom extends MySqlTypeConvert implements ITypeConvert {

    @Override
    public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
        String t = fieldType.toLowerCase();
        if (t. contains("tinyint(1)")) {
            return DbColumnType. INTEGER;
        }
        return super.processTypeConvert(globalConfig, fieldType);
    }
}