MybatisPlus code generator

AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be generated quickly. Greatly improved the development efficiency. So this article describes how to use MyBatis-Plus code generator.

Integrate Mybatis-Plus code generator based on Spring

Create the Spring project and import the dependencies

<dependencies>
<! --mp core dependencies -->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
  </dependency>
  <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
  </dependency>
  <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
  </dependency>
<! - mysql driver - >
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.47</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
Copy the code

Create CodeGeneratorTest file under test file

public class CodeGeneratorTest {
  /** * 

* read the console contents *

*/
@Test public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("Please enter" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); } public static void main(String[] args) { // Code generator AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); // Get the current system directory String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("author"); // Generate author comments gc.setOpen(false); // Whether to open the resource manager gc.setFileOverride(false); // Whether the file is overwritten during the rebuild gc.setServiceName("%sService"); // Remove the initial letter I of the Service interface gc.setDateType(DateType.ONLY_DATE);// Define the date type in the generated entity class gc.setSwagger2(false);// Enable Swagger2 mode mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mp? useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); // Database type dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); / / package configuration PackageConfig pc = new PackageConfig(); pc.setModuleName("test"); // Module name, optional // Which package to put under, the parent package name. If it is empty, the next package name must be written all, otherwise only the subpackage name is written pc.setParent("com.mybatis"); pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // Customize package configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { // to do nothing}};// If the template engine is freemarker String templatePath = "/templates/mapper.xml.ftl"; // If the template engine is Velocity // String templatePath = "/templates/mapper.xml.vm"; // Customize the output configuration List<FileOutConfig> focList = new ArrayList<>(); // Custom configurations are printed first focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);// Configure the template TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // Policy configuration StrategyConfig strategy = new StrategyConfig(); // The naming strategy for database tables mapped to entities strategy.setNaming(NamingStrategy.underline_to_camel); // Naming policy for database table field mapping to entity, not specified as naming execution strategy.setColumnNaming(NamingStrategy.underline_to_camel); // Define the full name of the inherited Entity class, including the package name strategy.setSuperEntityClass("Your own parent entity, no need to set!"); // Lombok model (default false) strategy.setEntityLombokModel(true); // Generate the @restController controller strategy.setRestControllerStyle(true); // Public parent class strategy.setSuperControllerClass("Your own parent controller, no need to set!"); // Public fields written in the parent class strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code

Open the directory to see the generated files

Integrate Mybatis-Plus code generator based on SpringBoot

Create a SpringBoot project

Introduction of depend on

 
      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.3.5. RELEASE</version>
  <relativePath/> <! -- lookup parent from repository -->
</parent>
<groupId>com.lagou</groupId>
<artifactId>springBoot-mp-generator</artifactId>
<version>0.0.1 - the SNAPSHOT</version>
<name>mp-generator</name>
<description>Demo project for Spring Boot</description>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>

  <! -- Springboot support for Mybatis -->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.1.1</version>
  </dependency>
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.1.1</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
  </dependency>
  <! - mysql driver - >
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </dependency>

</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>
</project>
Copy the code

Create CodeGeneratorTest file under test file

public class CodeGenerator {

  /** * 

* read the console contents *

*/
public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("Please enter" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); } /** * RUN THIS */ public static void main(String[] args) { // Code generator AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); final String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("author"); gc.setOpen(false); mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / mp? useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); / / package configuration final PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("Module name")); pc.setParent("com.mybatis.mp.generator"); mpg.setPackageInfo(pc); // Custom configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { // to do nothing}}; List<FileOutConfig> focList =new ArrayList<FileOutConfig>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // Customize the input file name return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity"); strategy.setEntityLombokModel(true); // strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController"); strategy.setInclude(scanner("The name of the table")); strategy.setSuperEntityColumns("id"); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); // Select freemarker engine to specify the following addition, note that poM dependencies must have! mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code

Test and verify

Common configuration for code generators

The data source dataSourceConfig is configured

  • dbQuery

By default, the database information query class is determined by the dbType type. The built-in implementation of the database is selected. The IDbQuery interface is used to customize the database query SQL statement

  • dbType

Database types This class has common database types built in [required]

  • schemaName

Database schema name For example, PostgreSQL can be set to public

  • typeConvert

By default, the type conversion is determined by the dbType. The built-in database implementation is used to convert the database field types defined by the ITypeConvert interface to the Required Java type. The built-in conversion type cannot meet the user-defined IColumnType interface

  • url

The URL that drives the connection

  • driverName

Driver name

  • username

Database connection user name

  • password

Database connection password

Database table Configuration

  • isCapitalMode

Uppercase name

  • skipView

Whether to skip view

  • naming

Naming strategy for mapping database tables to entities

  • columnNaming

Naming policy for database table field mapping to entity, not specified as naming execution

  • 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

  • superServiceClass

The full name of the user-defined inherited Service class, including the package name

  • 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 (since 3.3.1)

If likeTable and notLikeTable are disabled, include and exclude will use memory filtering. If you have SQL syntax compatibility problems, manually set this parameter to false. MyCat middleware, opens New Window support

  • include

Table name to include. When enableSqlFilter is false, regular expressions are allowed (optional with exclude).

  • likeTable

As of 3.3.0, fuzzy matching table names (optionally configured with notLikeTable)

  • exclude

Name of the table to exclude. When enableSqlFilter is false, regular expressions are allowed

  • notLikeTable

Since 3.3.0, obfuscate excludes table names

  • entityColumnConstant

[entity] Whether to generate field constants (default false)

  • entityBuilderModel

[Entity] Whether it is the Builder model (default false), renamed chainModel as of 3.3.2

  • ChainModel (since 3.3.2)

[Entity] Chained model (default false)

  • entityLombokModel

[Entity] Lombok model (default false)

3.3.2 The following version generates chainModel by default. After 3.3.2, it does not generate chainModel by default. Please enable chainModel if necessary

  • entityBooleanColumnRemoveIsPrefix

Boolean whether to remove is prefix from type fields (default false)

  • restControllerStyle

Generate the @restController controller

  • controllerMappingHyphenStyle

Hump to hyphen

  • entityTableFieldAnnotationEnable

Generate field annotations when generating entities or not

  • versionFieldName

Optimistic lock property name

#logicDeleteFieldName Logical delete attribute name

  • tableFillList

Table fill field

The package name configuration

  • parent

The father package name. If it is empty, the next package name must be written all, otherwise only the subpackage name is written

  • moduleName

Parent package module name

  • entity

The Entity package name

  • service

The Service package name

  • serviceImpl

Service Impl package name

  • mapper

Mapper package name

  • xml

Mapper XML package name

  • controller

The Controller package name

  • pathInfo

Path Configuration Information

The template configuration

  • entity

Java entity class template

  • entityKt

Kotin entity class template

  • service

The Service class template

  • serviceImpl

The Service Impl implements the class template

  • mapper

Mapper template

  • xml

Mapper XML template

  • controller

Controller Controller template

Global policy globalConfig configuration

  • outputDir

The default output directory of the generated file is the root directory of drive D

  • fileOverride

Overwrite existing files Default value: false

  • open

Whether to enable the output directory Default value: true #enableCache Whether to add level 2 cache configuration to XML Default value: false

  • author

Developer default: null

  • kotlin

Enable Kotlin mode Default value: false

  • swagger2

Enable Swagger2 Mode Default: false

  • activeRecord

Enable the ActiveRecord mode default value: false

  • baseResultMap

Enable BaseResultMap Default value: false

  • baseColumnList

Enable baseColumnList Default value: false

  • dateType

Time type Policy Default value: TIME_PACK Note: %s is the placeholder as follows

  • entityName

Entity naming mode Default value: null Example: %sEntity generates UserEntity

  • mapperName

Mapper Naming mode Default value: null Example: %sDao Generates the UserDao

  • xmlName

Mapper XML Naming mode Default value: NULL For example, %sDao generates userdao.xml

  • serviceName

Service Naming mode Default value: null For example, %sBusiness generates UserBusiness

  • serviceImplName

Service ImpL Naming mode Default value: NULL For example, %sBusinessImpl Generates UserBusinessImpl

  • controllerName

Controller naming mode Default value: null For example, %sAction Generates UserAction

  • idType

Specifies the ID type of the generated primary key. Default: NULL

Injection injectionConfig configuration

  • map

Custom returns configuration Map objects that can be passed to the template engine via cfg.xxx references

  • fileOutConfigList

User-defined output file configuration FileOutConfig Specifies the template file and output file to generate user-defined files

  • fileCreate

This configuration is used to determine whether a class needs to be overridden or not. Of course, you can implement your own differential algorithm merge file

  • initMap

Inject a custom Map object (note that setMap is required)

For more information on Mybatis-Plus code generator configuration, see the official website. MybatisPlus code generator website