This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021


MyBatis – Plus the official document: mp.baomidou.com/guide/gener…

This is the document on the official website. From the official document for the rapid generation of code, it can be seen that the configuration structure of code generator is:


    //1. Configure data source
    FastAutoGenerator.create("url"."username"."password")
        //2
        .globalConfig(...)
        //3
        .packageConfig(...)
        //4
        .strategyConfig(...)
        // Configure the template engine
        .templateEngine(...)
        / / 6, execution
        .execute();

Copy the code

Fill in the blanks to configure DataSource, GlobalConfig, PackageConfig, StrategyConfig, and TemplateEngine.

The official documentation also shows what we can do for each configuration.

configuration

DataSource configuration (DataSource)

attribute instructions The sample
url JDBC path JDBC: mysql: / / 127.0.0.1:3306 / mybatis – plus
username Database account root
password Database password 123456
dbQuery(IDbQuery) Database query new MySqlQuery()
schema(String) Database Schema (Applicable to some databases) mybatis-plus
typeConvert(ITypeConvert) Database type converter new MySqlTypeConvert()
keyWordsHandler(IKeyWordsHandler) Database keyword processor new MySqlKeyWordsHandler()

Global Configuration (GlobalConfig)

methods instructions The sample
fileOverride Overwrite the generated file Default value: false
disableOpenDir Disallow opening the output directory Default value: true
outputDir(String) Specify the output directory /opt/baomidou/ Default value: Windows :D:// Linux or MAC :/ TMP
author(String) The author’s name Baomidou Default value: author
enableKotlin Enable Kotlin mode Default value: false
enableSwagger Turn on Swagger mode Default value: false
dateType(DateType) Time strategy Datetype. ONLY_DATE=Date Default value: datetype. TIME_PACK=LocalDateTime
commentDate(String) Comment date Default value: YYYY-MM-DD

Package Configuration (PackageConfig)

methods instructions The sample
parent(String) The parent package name Default value: com. Baomidou
moduleName(String) Parent package module name Default value: none
entity(String) The Entity package name Default value: the entity
service(String) The Service package name Default value: service
serviceImpl(String) Service Impl package name Default value: service. Impl
mapper(String) Mapper package name Default value: mapper
mapperXml(String) Mapper XML package name Default value: mapper XML
controller(String) The Controller package name Default value: the controller
other(String) Custom file package name The package name used to output the custom file
pathInfo(Map<OutputFile, String>) Path Configuration Information Collections.singletonMap(OutputFile.mapperXml, “D://”)

Policy Configuration (StrategyConfig)

methods instructions The sample
enableCapitalMode Turn on uppercase naming Default value: false
enableSkipView Enable Skip View Default value: false
disableSqlFilter Disabling SQL Filtering Default value :true. If the syntax does not support SQL filtering, you can disable this function
enableSchema Enable the schema Default value :false, enabled in multiple schema scenarios
likeTable(LikeTable) Fuzzy table matching (SQL filtering) Only one item can be configured for likeTable and notLikeTable
notLikeTable(LikeTable) Fuzzy table exclusion (SQL filtering) Only one item can be configured for likeTable and notLikeTable
addInclude(String…) Add table matches (memory filtering) Only one include and exclude can be configured
addExclude(String…) Added table exclusion matches (memory filtering) Only one include and exclude can be configured
addTablePrefix(String…) Added the filter table prefix
addTableSuffix(String…) Add the suffix to the filter table
addFieldPrefix(String…) Add the filter field prefix
addFieldSuffix(String…) Add the suffix of a filter field
entityBuilder Entity Policy Configuration
controllerBuilder Controller Policy Configuration
mapperBuilder Mapper policy configuration
serviceBuilder Service Policy Configuration

TemplateEngine Configuration

The default Velocity; Optional template engines Beetl or Freemarker.

A template engine code
Velocity The default .templateEngine(new VelocityTemplateEngine())
Freemarker optional .templateEngine(new FreemarkerTemplateEngine())
Beetl optional .templateEngine(new BeetlTemplateEngine())

Code generator test sample

So once we know the configuration we can write our own operation.

Steps:

Create test database MP

CREATE DATABASE mp;

USE `mp`;

/*Table structure for table `student` */

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'student id',
  `name` varchar(50) DEFAULT NULL COMMENT 'name',
  `score` double DEFAULT NULL COMMENT 'results'.PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `user` */

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'user id',
  `username` varchar(50) NOT NULL COMMENT 'Username',
  `password` varchar(50) DEFAULT NULL COMMENT 'password',
  `create_time` date DEFAULT NULL COMMENT 'Creation time',
  `modify_time` date DEFAULT NULL COMMENT 'Last modified time'.PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code
Field Type Comment
id int The user id
username varchar(50) The user name
password varchar(50) password
create_time date Creation time
modify_time date The time was last changed
Field Type Comment
id int Student id
name varchar(50) The name
score double results

Create a spring-boot project

Import the dependencies in pom.xml

<! --spring-boot-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! --SpringBootTest-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<! --swagger-->
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.6.3</version>
</dependency>
<! --lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<! - mysql driver - >
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>
<! --mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.4</version>
</dependency>
<!--mybatis-plus-generator 生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1 track of</version>
</dependency>
<! --velocity-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>
<! --freemarker-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>
<! - beetl template - >
<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.8.1. RELEASE</version>
</dependency>
Copy the code

Note: In the template engine configuration, Beetl or Freemarker can be selected as the default Velocity template engine. In actual use, only the corresponding dependencies of the template can be imported, not all of them can be imported.

4. Write a mian method and add the framework

public static void main(String[] args) {
    //1. Configure data source
    FastAutoGenerator.create("url"."username"."password")
        //2
        .globalConfig(...)
        //3
        .packageConfig(...)
        //4
        .strategyConfig(...)
        // Configure the template engine
        .templateEngine(...)
        / / 6, execution
        .execute();
}
Copy the code

5. Configure the data source

public static void main(String[] args) {
    //1. Configure data source
    FastAutoGenerator.create("jdbc:mysql://localhost:3306/mp"."root"."123456")
        //2
        .globalConfig(...)
        //3
        .packageConfig(...)
        //4
        .strategyConfig(...)
        // Configure the template engine
        .templateEngine(...)
        / / 6, execution
        .execute();
}
Copy the code

6. Perform global configuration

Note: Support for lambda expressions began in version 3.5.1+

	//2
	.globalConfig(builder -> {
    	builder.author("Jie") // Set the author name
        	.outputDir(System.getProperty("user.dir") + "/src/main/java")   // Set the output path
        	.commentDate("yyyy-MM-dd hh:mm:ss")   // Comment the date
        	.dateType(DateType.ONLY_DATE)   // Define the type of the date in the generated entity class TIME_PACK=LocalDateTime; ONLY_DATE=Date;
        	.fileOverride()   // Overwrite the previous file
        	.enableSwagger()   // Enable swagger mode
        	.disableOpenDir();   // Disable the opening of the output directory
	});
Copy the code

7. Configure the package

	//3
	.packageConfig(builder -> {
    	builder.parent("com") // Set the parent package name
        	.moduleName("mp")   // Set the module package name
        	.entity("entity")   // PoJO entity class package name
        	.service("service") / / Service package name
        	.serviceImpl("serviceImpl") / / * * * ServiceImpl package name
        	.mapper("mapper")   / / Mapper package name
        	.xml("mapper")  / / Mapper XML package name
        	.controller("controller") / / Controller package name
        	.other("utils") // Customize the package name
        	.pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") +"/src/main/resources/mapper"))    // Configure ** mapper. XML path information: project resources directory in Mapper directory
	});
Copy the code

8. Configure policies

In policy configuration, generate policies of Mapper, Service, Entity, and Controller classes need to be configured separately.

	//4
	.strategyConfig(builder -> {
    	builder.addInclude("user"."student") // Set the name of the table to be generated
        	.addTablePrefix("t_"."c_") // Set the filter table prefix

            4.1. Configure the Mapper policy
        	.mapperBuilder()
        	.superClass(BaseMapper.class)   // Set the parent class
        	.formatMapperFileName("%sMapper")   // Format the mapper file name
        	.enableMapperAnnotation()       // Enable @mapper annotation
        	.formatXmlFileName("%sXml"); // Format the Xml file name
        
        	// configure the service policy
        	.serviceBuilder()
        	.formatServiceFileName("%sService") // Format the service interface file name, %s to match the table name, such as UserService
        	.formatServiceImplFileName("%sServiceImpl") // Format the service implementation class file name. %s matches the table name, such as UserServiceImpl

        	//4.3. Entity-class Policy Configuration
        	.entityBuilder()
        	.enableLombok() / / open Lombok
        	.disableSerialVersionUID()  // Do not implement Serializable interface, do not produce SerialVersionUID
        	.logicDeleteColumnName("deleted")   // Logically delete field name
        	.naming(NamingStrategy.underline_to_camel)  // Database table mapping entity naming strategy: underline to hump
        	.columnNaming(NamingStrategy.underline_to_camel)    // Database table field mapping entity naming strategy: underline to hump
        	.addTableFills(
        		new Column("create_time", FieldFill.INSERT),
        		new Column("modify_time", FieldFill.INSERT_UPDATE)
    		)   // Add table field fill, "create_time" field is automatically filled to insert time, "modify_time" field is automatically filled to insert change time
        	.enableTableFieldAnnotation()       // Generate field annotations when generating entities is enabled

        	4.4. Configure the Controller policy
        	.controllerBuilder()
        	.formatFileName("%sController") // Format the Controller class file name, %s to match the table name, such as UserController
        	.enableRestStyle()  // Enable the @restController controller generation function
        	
})
Copy the code

9. Template engine configuration

	//5
	.templateEngine(new VelocityTemplateEngine())	/ / the default
    /* .templateEngine(new FreemarkerTemplateEngine()) .templateEngine(new BeetlTemplateEngine()) */
Copy the code

10, execute,

	/ / 6, execution
	.execute();
Copy the code

Execution effect demonstration:

Note: the interactive generation of attachment 2 is used here, and there is almost no difference between the source code.

Attachment 1: Quick generation of sample code


public static void main(String[] args) {
    //1. Configure data source
    FastAutoGenerator.create("jdbc:mysql://localhost:3306/mp"."root"."123456")
        //2
        .globalConfig(builder -> {
            builder.author("Jie") // Set the author name
                .outputDir(System.getProperty("user.dir") + "/src/main/java")   // Set the output path: in the Java directory of the project
                .commentDate("yyyy-MM-dd hh:mm:ss")   // Comment the date
                .dateType(DateType.ONLY_DATE)   // Define the type of the date in the generated entity class TIME_PACK=LocalDateTime; ONLY_DATE=Date;
                .fileOverride()   // Overwrite the previous file
                .enableSwagger()   // Enable swagger mode
                .disableOpenDir();   // Disable the opening of the output directory
        })
        //3
        .packageConfig(builder -> {
            builder.parent("com") // Set the parent package name
                .moduleName("mp")   // Set the module package name
                .entity("entity")   // PoJO entity class package name
                .service("service") / / Service package name
                .serviceImpl("serviceImpl") / / * * * ServiceImpl package name
                .mapper("mapper")   / / Mapper package name
                .xml("mapper")  / / Mapper XML package name
                .controller("controller") / / Controller package name
                .other("utils") // Customize the package name
                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") +"/src/main/resources/mapper"))    // Configure mapper. XML path information: in the resources directory of the project
        })
        //4
        .strategyConfig(builder -> {
            builder.addInclude("user"."student") // Set the name of the table to be generated
                .addTablePrefix("t_"."c_") // Set the filter table prefix

                4.1. Configure the Mapper policy
                .mapperBuilder()
                .superClass(BaseMapper.class)   // Set the parent class
                .formatMapperFileName("%sMapper")   // Format the mapper file name
                .enableMapperAnnotation()       // Enable @mapper annotation
                .formatXmlFileName("%sXml"); // Format the Xml file name

            	// configure the service policy
            	.serviceBuilder()
                .formatServiceFileName("%sService") // Format the service interface file name, %s to match the table name, such as UserService
                .formatServiceImplFileName("%sServiceImpl") // Format the service implementation class file name. %s matches the table name, such as UserServiceImpl

                //4.3. Entity-class Policy Configuration
                .entityBuilder()
                .enableLombok() / / open Lombok
                .disableSerialVersionUID()  // Do not implement Serializable interface, do not produce SerialVersionUID
                .logicDeleteColumnName("deleted")   // Logically delete field name
                .naming(NamingStrategy.underline_to_camel)  // Database table mapping entity naming strategy: underline to hump
                .columnNaming(NamingStrategy.underline_to_camel)    // Database table field mapping entity naming strategy: underline to hump
                .addTableFills(
                new Column("create_time", FieldFill.INSERT),
                new Column("modify_time", FieldFill.INSERT_UPDATE)
            )   // Add table field fill, "create_time" field is automatically filled to insert time, "modify_time" field is automatically filled to insert change time
                .enableTableFieldAnnotation()       // Generate field annotations when generating entities is enabled

                4.4. Configure the Controller policy
                .controllerBuilder()
                .formatFileName("%sController") // Format the Controller class file name, %s to match the table name, such as UserController
                .enableRestStyle()  // Enable the @restController controller generation function
        })
        / / 5, and templates
        .templateEngine(new VelocityTemplateEngine())
        /* .templateEngine(new FreemarkerTemplateEngine()) .templateEngine(new BeetlTemplateEngine()) */
        / / 6, execution
        .execute();
}

Copy the code

Attachment 2: Interactive generation of sample code

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("= = = = = = = = = = = = = = = = = = = = = database configuration = = = = = = = = = = = = = = = = = = = = = = =");
    System.out.println("Please enter URL");
    String url = scan.next();
    System.out.println("Please enter username");
    String username = scan.next();
    System.out.println("Please enter password");
    String password = scan.next();

    FastAutoGenerator.create(url, username, password)
        // Global configuration
        .globalConfig((scanner, builder) -> builder.author(scanner.apply("= = = = = = = = = = = = = = = = = = = = = global configuration = = = = = = = = = = = = = = = = = = = = = = = \ n please enter the author name?"))
                      .outputDir(System.getProperty("user.dir") + "/src/main/java")
                      .commentDate("yyyy-MM-dd hh:mm:ss")
                      .dateType(DateType.TIME_PACK)
                      .enableSwagger()
                      .fileOverride()
                      .enableSwagger()
                      .disableOpenDir()
                     )
        / / package configuration
        .packageConfig((scanner, builder) -> builder.parent(scanner.apply("= = = = = = = = = = = = = = = = = = = = = package configuration = = = = = = = = = = = = = = = = = = = = = = = \ n please enter the package name?"))
                       .moduleName(scanner.apply("Please enter the module name of the parent package?"))
                       .entity("entity")
                       .service("service")
                       .serviceImpl("serviceImpl")
                       .mapper("mapper")
                       .xml("mapper")
                       .other("utils")
                       .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") +"/src/main/resources/mapper")))// Policy configuration
        .strategyConfig((scanner, builder) -> {
            builder.addInclude(getTables(scanner.apply("= = = = = = = = = = = = = = = = = = = = = policy configuration = = = = = = = = = = = = = = = = = = = = = = = \ n please input the name of the table, multiple commas in English? All type all")))
                .serviceBuilder()
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImpl")
                .entityBuilder()        // Entity-class policy configuration
                .enableLombok()         / / open Lombok
                .disableSerialVersionUID()
                .logicDeleteColumnName("deleted")        // Delete fields logically
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                .addTableFills(new Column("create_time", FieldFill.INSERT), new Column("modify_time", FieldFill.INSERT_UPDATE))
                .enableTableFieldAnnotation()       // Generate field annotations when generating entities is enabled
                .controllerBuilder()
                .formatFileName("%sController")
                .enableRestStyle()
                .mapperBuilder()
                .superClass(BaseMapper.class)
                .formatMapperFileName("%sMapper")
                .enableMapperAnnotation()       //@mapper
                .formatXmlFileName("%sMapper");
        })
        /* Template engine configuration, Default Velocity optional templateEngine Beetl or freemarker.templateengine (new BeetlTemplateEngine()).templateengine (new) FreemarkerTemplateEngine()) */
        .execute();
}

// Handle all
protected static List<String> getTables(String tables) {
    return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
Copy the code