[Benefits, users commenting on this article will have a chance to get a new nugget badge]

preface

XDM Hello everyone, this is the golden autumn season. He had a full day of training in August. A new event will come out in late August: a free opportunity to apply for nuggets perimeter gifts. Holding the idea of trying, submitted an application, for the majority of digging friends to apply for welfare. The author is lucky to get the quota of the first trial phase. Thanks for readers’ recognition of little Ajie for a long time, and thanks to Nuggets for providing this opportunity to make the author and readers better interact.

The link to the campaign is as follows: Please check | you have a free opportunity to apply for nuggets peripheral gifts

Messages received in the System station:

The list published on the official website. After the success of the surrounding activities received the application, we also carried out sufficient technical topic selection, which could not only output technical knowledge, but also fully mobilize the active interaction of readers. After careful consideration, I chose to write code generation and some thoughts on the use of code generators in projects to discuss these issues.To get started, the code generator is the AutoGenerator in MyBatis-Plus.

I met AutoGenerator.

I believe that the use of code generator partners feel very cool, brush brush basic code has been developed. There is a code generator that is often used during the Java startup process, called AutoGenerator. AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be quickly generated, which greatly improves the development efficiency. Reduced duplication of basic code.

Fedex started

Add the dependent

MyBatis-Plus removed the default dependencies for code generators and template engines after 3.0.3, requiring manual addition of dependencies: This article is for Java developers, using Maven to import dependency package information.

<! -- mybatis-plus --><dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.29</version>
        </dependency><! -- mybatis-plus -->Copy the code

The basic configuration

In using an AutoGenerator code generator, the parameters need to be configured to generate the code. The configuration includes data source configuration, database table configuration, package name configuration, template configuration, global policy configuration, and injection configuration. The following describes the parameters and their functions.

Data Source Configuration

The data source configuration DataSourceConfig, whose default value is NULL, specifies the specific database to which code is to be generated.

The parameter types describe note
dbQuery Database information query class The default is determined by the dbType type and the corresponding database built-in implementation is selected
dbType Database type This class has common database types built in [required]
schemaName Database Schema name For example, PostgreSQL can be specified as public
typeConvert Type conversion The default is determined by the dbType type and the corresponding database built-in implementation is selected
url The URL that drives the connection The link address of the database
driverName Driver name For example: com. Mysql. Cj). The JDBC Driver
username Database connection user name Database connection user name
password Database connection password Database connection password

Database table Configuration

The database table configuration StrategyConfig, whose default value is NULL, specifies which tables to generate or exclude.

The parameter types describe Note and default value
isCapitalMode Uppercase name false
skipView Whether to skip view false
naming Naming strategy for mapping database tables to entities
columnNaming Naming policy for database table field mapping to entity, not specified as naming execution null
tablePrefix The table prefix
fieldPrefix Field prefix
superEntityClass The full name of the user-defined inherited Entity class, including the package name
superEntityColumns Custom base Entity class, public field
superMapperClass The full name of a user-defined inherited Mapper class, including the package name String SUPER_MAPPER_CLASS = “com.baomidou.mybatisplus.core.mapper.BaseMapper”;
superServiceClass The full name of the user-defined inherited Service class, including the package name String SUPER_SERVICE_CLASS = “com.baomidou.mybatisplus.extension.service.IService”;
superServiceImplClass The full name of the inherited ServiceImpl class, including the package name
superControllerClass The full name of the inherited Controller class, including the package name
enableSqlFilter If likeTable and notLikeTable are disabled, include and exclude will use memory filtering. If you have SQL syntax compatibility problems, manually set it to false
include Table name to be included. When enableSqlFilter is false, regular expressions (or exclude) are allowed null
likeTable As of 3.3.0, fuzzy matching table names (optionally configured with notLikeTable) likeTable
exclude Name of the table to exclude. When enableSqlFilter is false, regular expressions are allowed null
notLikeTable Since 3.3.0, obfuscate excludes table names null
entityColumnConstant [entity] Whether to generate field constants (default false) false
chainMode [Entity] Whether it is the builder model (default false) 3.3.2 Start The original version was entityBuilderModel
entityLombokModel [Entity] Lombok model (default false) 3.3.2 The following versions generate chained models by default. After 3.3.2,
entityBooleanColumnRemoveIsPrefix Boolean whether to remove is prefix from type fields (default false) false
restControllerStyle Generate the @restController controller false
controllerMappingHyphenStyle Hump to hyphen false
entityTableFieldAnnotationEnable Generate field annotations when generating entities or not false
versionFieldName Optimistic lock property name
logicDeleteFieldName Logical delete attribute name is_del
tableFillList Table fill field

The package name configuration

The PackageConfig configuration, whose default value is NULL, specifies the package path to generate code.

The parameter types describe The default value
parent The father package name. If it is empty, the next package name must be written all, otherwise only the subpackage name is written com.baomidou
moduleName Parent package module name null
entity The Entity package name entity
service The Service package name service
serviceImpl Service Impl package name service.impl
mapper Mapper mapper
xml Mapper XML package name mapper.xml
controller The Controller package name controller
pathInfo Path Configuration Information

The template configuration

Template configuration TemplateConfig, its default value: NULL, can be customized code generation template, to achieve personalized operation.

The parameter types describe note
entity Java entity class template /templates/entity.java
entityKt Kotin entity class template /templates/entity.kt
service The Service class template /templates/service.java
serviceImpl The Service Impl implements the class template /templates/serviceImpl.java
mapper Mapper template /templates/mapper.java
xml Mapper XML template /templates/mapper.xml
controller Controller Controller template /templates/controller.java

Global Policy Configuration

Global policy configuration GlobalConfig, whose default value is NULL.

The parameter types describe note
outputDir Generate the output directory of the file Default value: root directory of drive D
fileOverride Whether to overwrite an existing file Default value: false
open Whether to open the output directory Default value: true
enableCache Whether to add a second-level cache configuration to the XML Default: ‘false’
author The developer Default value: null
kotlin Enable Kotlin mode Default value: false
swagger2 Enable Swagger2 mode Default value: false
activeRecord Enable the ActiveRecord mode Default value: false
baseResultMap Open BaseResultMap Default value: false
baseColumnList Open baseColumnList Default value: false
dateType The time type corresponds to the policy Default value: TIME_PACK
entityName Entity naming Default value: NULL Example: %sEntity generates UserEntity
mapperName Mapper naming mode Default value: NULL For example: %sDao Generates UserDao
xmlName Mapper XML naming mode Default: NULL For example: %sDao generates userdao.xml
serviceName Service naming Default: null For example: %sBusiness Generates UserBusiness
serviceImplName Service IMPL naming mode Default value: NULL For example: %sBusinessImpl Generates UserBusinessImpl
controllerName Controller naming Default value: null For example: %sAction Generates UserAction
idType Specifies the ID type of the generated primary key Default value: null

Injection allocation

InjectionConfig. The default value is null. Through this configuration, you can inject custom parameters and other operations to achieve personalized operations.

The parameter types describe note
map User-defined Returns the configuration Map object The object can be passed to the template engine via cfg.xxx reference
fileOutConfigList Customize the output file Configure FileOutConfig to specify template files and output files to generate customized files
fileCreate Custom determines whether to create a file Implement IFileCreate interface
initMap Inject a custom Map object (note that setMap is required)

With the configuration information described above, MyBatis-Plus’s AutoGenerator code generator provides a large number of custom parameters that can be used by most people. Let’s write the code for the above configuration. DataSourceConfig, StrategyConfig, PackageConfig, TemplateConfig, GlobalConfig, InjectionConfig, etc.

The sample

Set the constant

 /** * The name of the table to be generated ** /
    private static final String[] TABLE_NAMES = new String[] {"z_seo"};
    /** * File path ** /
    public static final String PROJECT_PATH = "E:\\bootproject\\BootDemo\\";
    //
    /** * Project name ** /
    public static final String PROJECT_NAME = "18BootAutoGenerator";
    /** * Module name ** /
    public static final String MODULE_NAME ="";

    /** * Data source configuration ** /
    public static final String DATA_SOURCE_URL ="JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior" +
            "=convertToNull";
    public static final String DATA_SOURCE_USERNAME ="test";
    public static final String DATA_SOURCE_PASSWORD ="123456";
    public static final String DATA_SOURCE_DRIVERNAME ="com.mysql.cj.jdbc.Driver";
Copy the code

Initialize the code generator

     / * * *@MethodName: main
     * @Description: code generator *@Return: 
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
    public static void main(String[] args) {
            // Code generator
            AutoGenerator autoGenerator = new AutoGenerator();
            autoGenerator.setDataSource(getDataSourceConfigInfo());
            autoGenerator.setGlobalConfig(getGlobalConfigInfo());
            autoGenerator.setPackageInfo(getPackageConfigInfo());
            autoGenerator.setStrategy(getStrategyConfigInfo(TABLE_NAMES));
            autoGenerator.setTemplate(new TemplateConfig().setXml(null));
            autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
            autoGenerator.setCfg(getInjectionConfigInfo());
            autoGenerator.execute();
        }
Copy the code

Data Source Configuration

     / * * *@MethodName: getDataSourceConfigInfo
     * @Description: Data source configuration *@Return: DataSourceConfig
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
     public static DataSourceConfig getDataSourceConfigInfo() {
            DataSourceConfig dataSourceConfig = new DataSourceConfig();
            dataSourceConfig.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull");
            dataSourceConfig.setUsername("test");
            dataSourceConfig.setPassword("123456");
            dataSourceConfig.setDbType(DbType.MYSQL);
            dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
            return dataSourceConfig;
     }
Copy the code

Global configuration

     / * * *@MethodName: getGlobalConfigInfo
     * @Description: Global configuration *@Return: GlobalConfig
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
    public static GlobalConfig getGlobalConfigInfo() {
            // Global configuration
            GlobalConfig globalConfig = new GlobalConfig();
    // String projectPath = System.getProperty("user.dir");
            globalConfig.setOutputDir(PROJECT_PATH + PROJECT_NAME + "/src/main/java/");
            globalConfig.setAuthor("JavaZhan");
            globalConfig.setOpen(false);
            globalConfig.setSwagger2(true);
            globalConfig.setBaseColumnList(true);
            globalConfig.setBaseResultMap(true);
            globalConfig.setActiveRecord(false);
            globalConfig.setFileOverride(true);
            globalConfig.setServiceName("%sService");
            return globalConfig;
        }
Copy the code

Package configuration

     / * * *@MethodName: getPackageConfigInfo
     * @Description: Package configuration *@Return: PackageConfig
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
     public static PackageConfig getPackageConfigInfo() {
            PackageConfig packageConfig = new PackageConfig();
            packageConfig.setParent("com.example.demo");
            packageConfig.setModuleName("test");
            packageConfig.setEntity("module");
            return packageConfig;
        }

Copy the code

Policy configuration

    / * * *@MethodName: getStrategyConfigInfo
     * @Description: Policy configuration *@Return: StrategyConfig
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
    public static StrategyConfig getStrategyConfigInfo(String. tableNames) {
            StrategyConfig strategyConfigInfo = new StrategyConfig();
            strategyConfigInfo.setCapitalMode(true);
            strategyConfigInfo.setNaming(NamingStrategy.underline_to_camel);
            // Underline the hump name
            strategyConfigInfo.setColumnNaming(NamingStrategy.underline_to_camel);
            // The name of the table to be generated
            strategyConfigInfo.setInclude(tableNames);
            // Set the logical delete field
            strategyConfigInfo.setLogicDeleteFieldName("data_state");
            / / use lombok
            strategyConfigInfo.setEntityLombokModel(true);
            // Set the table prefix
            strategyConfigInfo.setTablePrefix("");
            / / rest style
            strategyConfigInfo.setRestControllerStyle(true);

            return strategyConfigInfo;
        }
Copy the code

Abstract external interface

     / * * *@MethodName: getInjectionConfigInfo
     * @Description: Abstract external interface *@Return: InjectionConfig
     * @Author: JavaZhan @public id :Java full stack architect *@Date: 2021/9/8 * * /
    public static InjectionConfig getInjectionConfigInfo(){
            InjectionConfig injectionConfig = new InjectionConfig() {
                @Override
                public void initMap(){}}; List<FileOutConfig> focList =new ArrayList<FileOutConfig>();
            focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    / / output XML
                    return PROJECT_PATH + PROJECT_NAME + "/src/main/resources/mapper/" + MODULE_NAME
                            + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); injectionConfig.setFileOutConfigList(focList);return injectionConfig;
        }
Copy the code

perform

After the main method is initialized in the project, the following log is displayed, including module, Service, IMPL, mapper, XML and other related files.

The following figure, generated automatically generated files related to the file directory structure, the basic files we need have been generated.The following figure shows the entity object information we generated, including lombok and Swagger2 annotations, which can be configured in the GlobalConfig global configuration file if they are not needed.

Well, this article has covered the functionality of integrating AutoGenerator code generators based on Spring Boot and demonstrated the configuration. You can configure more detailed parameters according to specific requirements of the project to meet personalized requirements.

Thinking (Welcome to leave comments and exchange)

1. What are the drawbacks of using An AutoGenerator?

Do you have any common code generator recommendations to share?

3. What weird things have happened to using code generators?

What is your attitude toward code generators?

5. Discuss and learn the problems encountered in using AutoGenerator code generator.

Welcome to exchange your comments.

welfare

This article is: Please check | you have a free opportunity to apply for nuggets peripheral gifts, among all the comment users, there will be 2 lucky comment users, will receive nuggets new badges provided by the official 2.

Comment area Raffle Requirements (official requirements) :

  • By September 10th, if more than 10 people (not including the author) interact in the comments section, the author can draw 2 nuggets new badges in his own name (nuggets official bear).
  • By September 10th, if more than 10 people interact in the comments section (excluding the author) and the number of comments exceeds 20 (including the author), the author will get an extra gift from the nuggets.
  • TOP 1-5:1 new badge or 1 new IPT shirt in the comments section

The winning conditions

If the comments of this article meet the requirements of gold-digging activity, one lucky reader will be selected from the users in the gold-digging area as a gift of a new gold-digging badge. If there is no hot comment users, will be turned into comment lucky users.

If the comments of this article meet the requirements of the gold-digging activity, a lucky reader will be selected from all the users in the comment area to present a new gold-digging badge.

The lottery rules

On September 11, the lottery | night (Saturday afternoon), extracting random way.

conclusion

The project based on the Spring Boot integrated AutoGenerator code generator was completed, with a sloppy framework for fast code generation and of course more in-depth configuration parameters to meet personalized requirements. This article is mainly used for beginners to practice, but also as a basic query manual, I hope this article can help you. Thanks for reading.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.

Well, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.