Skip to content

Code Generator Configuration

The MyBatis-Plus code generator is a powerful tool that can automatically generate corresponding entity classes, Mapper interfaces, XML mapping files, and Service layer code based on database table structures. This tool significantly simplifies the development process based on the MyBatis framework and improves development efficiency, especially when dealing with a large number of database tables.

Main Features

  • Automation: The code generator can automatically generate corresponding Java code based on database table structures, reducing the workload of manually writing repetitive code.
  • Configurability: Through configuration files or code, you can flexibly specify the package path, table names, field names, templates, etc., to meet the needs of different projects.
  • Template Support: Supports custom code templates, allowing you to tailor code style and structure according to project requirements.
  • Multi-Database Support: Compatible with various database types, such as MySQL, Oracle, SQL Server, etc. Simply configure the corresponding database connection information.
  • Easy Integration: Can be easily integrated into existing projects—just a few lines of code are needed to start the code generation process.

Use Cases

  • New Project Setup: When starting a new project, you can use the code generator to quickly generate basic CRUD code, accelerating project initiation.
  • Table Structure Changes: When the database table structure changes, the code generator can update the corresponding Java code to maintain consistency between the code and the database.
  • Repetitive Tasks: In scenarios requiring a large amount of similar CRUD operations, the code generator can significantly reduce repetitive work and improve development efficiency.

How to Use

  1. Configure Data Source: Specify the database type, connection URL, username, password, etc.
  2. Configure Strategy: Select the tables for which code needs to be generated, set naming strategies for table and field names, etc.
  3. Configure Package Information: Set the package path for the generated code, including entity classes, Mapper interfaces, Service classes, etc.
  4. Configure Templates: If custom code styles are needed, configure or create custom code templates.
  5. Execute Generation: Run the code generator to produce the corresponding Java code based on the configuration.

Sample Code

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class CodeGenerator {
public static void main(String[] args) {
// Global configuration
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java") // Set output directory
.setAuthor("Your Name") // Set author
.setOpen(false) // Whether to open the directory after generation
.setFileOverride(true) // Whether to overwrite existing files
.setServiceName("%sService") // Service interface name suffix
.setIdType(IdType.AUTO) // Primary key generation strategy
.setSwagger2(true); // Whether to generate Swagger annotations
// Data source configuration
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL) // Database type
.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=UTC") // Database connection URL
.setUsername("root") // Database username
.setPassword("password") // Database password
.setDriverName("com.mysql.cj.jdbc.Driver"); // Database driver class name
// Strategy configuration
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setInclude("user", "order") // Tables to generate code for
.setNaming(NamingStrategy.underline_to_camel) // Table name to class name strategy
.setColumnNaming(NamingStrategy.underline_to_camel) // Column name to property name strategy
.setEntityLombokModel(true) // Use Lombok for entity classes
.setRestControllerStyle(true) // REST-style Controller
.setTablePrefix(new String[]{"tbl_"}); // Table name prefix
// Package configuration
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example") // Parent package name
.setMapper("mapper") // Mapper interface subpackage
.setEntity("entity") // Entity class subpackage
.setController("controller") // Controller subpackage
.setService("service") // Service subpackage
.setXml("mapper"); // Mapper XML file subpackage
// Template configuration
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null) // Disable XML generation
.setController("templates/controller.java.vm") // Controller template path
.setEntity("templates/entity.java.vm") // Entity template path
.setMapper("templates/mapper.java.vm"); // Mapper interface template path
// Integrate configurations
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig)
.setTemplate(templateConfig);
// Execute generation
autoGenerator.execute();
}
}

With the MyBatis-Plus code generator, developers can focus more on implementing business logic rather than writing repetitive CRUD code, thereby improving development efficiency and code quality.

Basic Configuration

Data Source Configuration (dataSource)

  • Type: DataSourceConfig
  • Default: null

The data source configuration is used to specify the target database for code generation. By configuring the data source, the code generator can connect to the database and retrieve table structure information to generate corresponding code.

Example Configuration:

DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL) // Set database type, such as MySQL, Oracle, etc.
.setUrl("jdbc:mysql://localhost:3306/mybatis_plus") // Database connection URL
.setUsername("root") // Database username
.setPassword("password") // Database password
.setDriverName("com.mysql.cj.jdbc.Driver"); // Database driver class name

Database Table Configuration (strategy)

  • Type: StrategyConfig
  • Default: null

The database table configuration is used to specify which tables to generate code for or exclude. Through strategy configuration, you can flexibly control the scope of code generation.

Example Configuration:

StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setInclude("user", "order") // Specify table names for code generation
.setExclude("user_detail") // Exclude table names from code generation
.setEntityLombokModel(true) // Enable Lombok model for entity classes
.setRestControllerStyle(true); // Set REST style for Controller

Package Configuration (packageInfo)

  • Type: PackageConfig
  • Default: null

Package configuration is used to specify the package path for generated code. By configuring the package names, you can ensure the generated code is placed in the correct directory structure.

Example Configuration:

PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example") // Set parent package name
.setMapper("mapper") // Set subpackage name for Mapper interfaces
.setEntity("entity") // Set subpackage name for entity classes
.setController("controller"); // Set subpackage name for Controllers

Template Configuration (template)

  • Type: TemplateConfig
  • Default: null

Template configuration allows customization of code generation templates to achieve personalized operations. Through template configuration, you can tailor the format and content of the generated code.

Example Configuration:

TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null) // Do not generate XML files
.setController("templates/controller.java.vm") // Set Controller template path
.setEntity("templates/entity.java.vm") // Set entity class template path
.setMapper("templates/mapper.java.vm"); // Set Mapper interface template path

Global Strategy Configuration (globalConfig)

  • Type: GlobalConfig
  • Default: null

Global strategy configuration provides some global settings, such as author information, output path, etc.

Example Configuration:

GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir("src/main/java") // Set the output directory for generated code
.setAuthor("Your Name") // Set author information
.setOpen(false) // Set whether to automatically open the directory after generation
.setFileOverride(true); // Set whether to overwrite when files exist

Injection Configuration (injectionConfig)

  • Type: InjectionConfig
  • Default: null

Injection configuration allows for operations such as injecting custom parameters to achieve personalized customization. Through injection configuration, additional logic can be added during the code generation process.

Example Configuration:

InjectionConfig injectionConfig = new InjectionConfig() {
// Custom injection parameters
@Override
public void initMap() {
// to do nothing
}
// Custom parameters
@Override
public MappedStatement injectMappedStatement(MappedStatement ms, Configuration configuration, SqlSource sqlSource, String mapperId) {
// Custom injection logic
return ms;
}
};

With the above configuration, the MyBatis-Plus code generator can produce code that aligns with your project structure based on your requirements, significantly improving development efficiency. Remember to adjust the configuration parameters according to your actual project needs to achieve optimal code generation results.

Data Source Configuration (dataSource) Explained

Data source configuration is a critical part of the MyBatis-Plus code generator, defining how to connect to the database and query database information. Below is a detailed explanation and examples of data source configuration.

dbQuery

  • Description: A database information query class used to perform database query operations.
  • Default Implementation: Automatically selects the built-in implementation for the corresponding database based on dbType.
  • Customization: You can implement the IDbQuery interface to customize database query SQL statements for returning specific content.

dbType

  • Description: Database type, a mandatory configuration option.
  • Built-in Support: MyBatis-Plus provides built-in support for various common database types, such as MySQL, Oracle, PostgreSQL, etc.

schemaName

  • Description: Database schema name, required by certain database systems (such as PostgreSQL).
  • Example: In PostgreSQL, it can be specified as public.

typeConvert

  • Description: Type conversion, used to convert database field types to Java types.
  • Default Implementation: Automatically selects the built-in implementation for the corresponding database based on dbType.
  • Customization: If the built-in conversion types do not meet requirements, you can implement the ITypeConvert interface to customize the conversion from database field types to Java types, or implement the IColumnType interface for more advanced customization.

url

  • Description: The URL for the database connection, containing all the information required to connect to the database.

driverName

  • Description: The name of the database driver, used to establish a database connection.

username

  • Description: The username for database connection, used for authentication.

password

  • Description: The password for database connection, used for authentication.

Example Configuration

DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL) // Set database type to MySQL
.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=UTC") // Set database connection URL
.setUsername("root") // Set database username
.setPassword("password") // Set database password
.setDriverName("com.mysql.cj.jdbc.Driver"); // Set database driver name

In this example, we have configured a data source for a MySQL database. We specified the database type, connection URL, username, password, and driver name. This information will be used to establish a connection to the database and retrieve table structure information to generate the corresponding Java code.

Please adjust these parameters according to your actual database configuration to ensure they match your database environment.

Database Table Configuration (strategy) Details

Database table configuration is used to define how database tables and fields are handled during code generation. Through strategy configuration, you can specify which tables to generate code for, how to name entity classes and fields, and whether to include specific annotations or attributes.

isCapitalMode

  • Description: Whether to use uppercase naming mode.
  • Default value: false

skipView

  • Description: Whether to skip the view.
  • Default value: false

naming

  • Description: The naming strategy for mapping database tables to entities.
  • Default value: Uses underscore to camel case naming.

columnNaming

  • Description: The naming strategy for mapping database table fields to entities.
  • Default Value: When unspecified, follows the naming strategy.

tablePrefix

  • Description: Table prefix, used to filter tables with specific prefixes.

fieldPrefix

  • Description: Field prefix, used to filter fields with a specific prefix.

superEntityClass

  • Description: The fully qualified name of the custom inherited Entity class, including the package name.

superEntityColumns

  • Description: Custom base Entity class, common fields.

superMapperClass

  • Description: The fully qualified name of the custom inherited Mapper class, including the package name.

superServiceClass

  • Description: The fully qualified name (including package name) of the custom inherited Service class.

superServiceImplClass

  • Description: The fully qualified name of the custom inherited ServiceImpl class, including the package name.

superControllerClass

  • Description: The fully qualified name of the custom inherited Controller class, including the package name.

enableSqlFilter Since 3.3.1

  • Description: By default, enables fuzzy table name matching in SQL. When disabled, likeTable and notLikeTable will become ineffective, and include and exclude will use in-memory filtering.
  • Default value: true
  • Note: If SQL syntax compatibility issues arise, manually set this to false. Known incompatible cases include the MyCat middleware. For more details, refer to ISSUE-2102.

include

  • Description: The table names to be included. When enableSqlFilter is false, regular expressions are allowed.

likeTable Since 3.3.0

  • Description: Fuzzy matching for table names. This should be configured alternatively with notLikeTable.

exclude

  • Description: Table names to be excluded. Regular expressions are allowed when enableSqlFilter is false.

notLikeTable Since 3.3.0

  • Description: Excludes table names with fuzzy matching. This and likeTable are mutually exclusive configurations.

entityColumnConstant

  • Description: Whether to generate field constants for the 【entity】.
  • Default value: false

entityBuilderModel @Deprecated

  • Description: Whether the [entity] is in builder model.
  • Default: false
  • Note: Renamed to chainModel since version 3.3.2

chainModel Since 3.3.2

  • Description: Whether the [entity] is a chain model.
  • Default value: false
  • Note: Versions prior to 3.3.2 generated chain models by default. Starting from 3.3.2, they are not generated by default. Enable this option if needed.

entityLombokModel

  • Description: Whether the 【entity】 is a Lombok model.
  • Default value: false

entityBooleanColumnRemoveIsPrefix

  • Description: Whether to remove the ‘is’ prefix for Boolean type fields.
  • Default value: false

restControllerStyle

  • Description: Generate @RestController controllers.
  • Default value: false

controllerMappingHyphenStyle

  • Description: Convert camelCase to hyphen-case.
  • Default value: false

entityTableFieldAnnotationEnable

  • Description: Whether to generate field annotations when generating entities.
  • Default value: false

versionFieldName

  • Description: The attribute name for optimistic locking.

logicDeleteFieldName

  • Description: The field name for logical deletion.

tableFillList

  • Description: Table fill fields.

Example Configuration

StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setCapitalMode(true) // Enable uppercase naming mode
.setEntityLombokModel(true) // Use Lombok model
.setRestControllerStyle(true) // Generate @RestController controllers
.setInclude("user", "order") // Include specific tables
.setExclude("user_detail") // Exclude specific tables
.setEntityBooleanColumnRemoveIsPrefix(true) // Remove 'is' prefix for Boolean fields
.setTablePrefix("tbl_") // Set table prefix
.setControllerMappingHyphenStyle(true); // Convert camelCase to hyphenated style

In this example, we configured a strategy specifying uppercase naming mode, using Lombok model, generating REST-style controllers, and defining tables to include/exclude. We also set table prefixes and camelCase-to-hyphen mapping style for controller routes.

Adjust these configuration parameters according to your project requirements to ensure the generated code meets your expectations.

Package Configuration (packageInfo) Explained

Package configuration is used to define the package structure of the generated code, ensuring that the generated code is placed in the correct directory. By configuring the package names, you can control how the code is organized to align with the project’s architectural design.

parent

  • Description: The parent package name, which serves as the top-level package for all generated code.
  • Default Value: If not specified, the full package path must be defined for each sub-package.

moduleName

  • Description: The parent package module name, used to distinguish between different modules or subsystems.

entity

  • Description: The package name for entities, i.e., the package name where the entity classes are located.

service

  • Description: The package name for Service, which is the package name where the service interfaces are located.

serviceImpl

  • Description: The package name for Service Impl, which is the package where service implementation classes are located.

mapper

  • Description: The package name for Mapper, which is the package where the Mapper interfaces are located.

xml

  • Description: The package name for Mapper XML, which is the package name where the Mapper XML files are located.

controller

  • Description: The package name for controllers, indicating the package where controller classes are located.

pathInfo

  • Description: Path configuration information used to specify the physical path for generated code.

Example Configuration

PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example") // Set parent package name
.setModuleName("mybatisplus") // Set parent module name
.setEntity("entity") // Set subpackage name for entity classes
.setService("service") // Set subpackage name for service interfaces
.setServiceImpl("service.impl") // Set subpackage name for service implementation classes
.setMapper("mapper") // Set subpackage name for Mapper interfaces
.setXml("mapper") // Set subpackage name for Mapper XML files
.setController("controller"); // Set subpackage name for controller classes

In this example, we have configured a package structure where the parent package name is com.example, and each subpackage name is set according to its functionality. For instance, entity classes will be placed in the com.example.mybatisplus.entity package, service interfaces will be placed in the com.example.mybatisplus.service package, and so on.

Please adjust these configuration parameters based on your project structure and organizational habits to ensure the generated code can be properly integrated into your project.

Template Configuration (template) Explained

Template configuration allows developers to customize the templates used by the code generator to produce code that aligns with the style and requirements of specific projects. The MyBatis-Plus code generator supports various types of templates, including entity classes, service classes, Mapper interfaces, XML mapping files, controller classes, and more.

entity

  • Description: Java entity class template, used for generating Java entity class code.

entityKt

  • Description: Kotlin entity class template, used for generating Kotlin entity class code.

service

  • Description: Service class template, used for generating service interface code.

serviceImpl

  • Description: Service impl implementation class template, used for generating service implementation class code.

mapper

  • Description: The mapper template, used for generating Mapper interface code.

xml

  • Description: The mapper xml template, used for generating Mapper XML mapping file code.

controller

  • Description: The controller template is used for generating controller class code.

Example Configuration

TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setEntity("templates/entity.java.vm") // Set entity class template path
.setService("templates/service.java.vm") // Set service class template path
.setServiceImpl("templates/serviceImpl.java.vm") // Set service implementation class template path
.setMapper("templates/mapper.java.vm") // Set Mapper interface template path
.setXml("templates/mapper.xml.vm") // Set Mapper XML template path
.setController("templates/controller.java.vm"); // Set controller template path

In this example, we have configured template paths for different types of files. For instance, the entity class template path is set to templates/entity.java.vm, the service class template path is set to templates/service.java.vm, and so on. These template paths point to custom template files in the project, which the code generator will use to produce the corresponding code.

Ensure your template file paths are correct and that the template files adhere to the syntax of template engines like Velocity or Freemarker. By customizing templates, you can control the structure, comments, naming conventions, and other aspects of the generated code to meet your project’s specific requirements.

In practical use, you may need to adjust template configurations based on your project’s needs. For example, if your project uses Kotlin, you would need to configure the entityKt template path. If your project does not require certain types of code (such as XML mapping files), you can omit the corresponding template configurations.

Global Strategy Configuration (globalConfig) Detailed Explanation

Global strategy configuration provides some global settings, such as output directory, file overwrite, developer information, etc., as well as some advanced options like Kotlin mode, Swagger2 integration, ActiveRecord mode, etc.

outputDir

  • Description: The output directory for generated files.
  • Default value: Root directory of D drive

fileOverride

  • Description: Whether to overwrite existing files.
  • Default value: false

open

  • Description: Whether to automatically open the output directory after generation.
  • Default value: true

enableCache

  • Description: Whether to add second-level cache configuration in XML.
  • Default value: false

author

  • Description: The name of the developer.
  • Default value: null

kotlin

  • Description: Whether to enable Kotlin mode.
  • Default value: false

swagger2

  • Description: Whether to enable Swagger2 mode.
  • Default value: false

activeRecord

  • Description: Whether to enable ActiveRecord mode.
  • Default value: false

baseResultMap

  • Description: Whether to enable BaseResultMap.
  • Default value: false

baseColumnList

  • Description: Whether to enable baseColumnList.
  • Default value: false

dateType

  • Description: The corresponding strategy for time type.
  • Default value: TIME_PACK

entityName

  • Description: The naming convention for entities, where %s acts as a placeholder.
  • Default Value: null
  • Example: %sEntity generates UserEntity

mapperName

  • Description: Naming convention for Mapper, where %s acts as a placeholder.
  • Default value: null
  • Example: %sDao generates UserDao

xmlName

  • Description: The naming convention for Mapper XML files, where %s acts as a placeholder.
  • Default Value: null
  • Example: %sDao generates UserDao.xml

serviceName

  • Description: The naming convention for Service, where %s acts as a placeholder.
  • Default value: null
  • Example: %sBusiness generates UserBusiness

serviceImplName

  • Description: Naming convention for Service impl, where %s is a placeholder.
  • Default value: null
  • Example: %sBusinessImpl generates UserBusinessImpl

controllerName

  • Description: Naming convention for Controller, where %s acts as a placeholder.
  • Default value: null
  • Example: %sAction generates UserAction

idType

  • Description: Specifies the ID type for the generated primary key.
  • Default value: null

Example Configuration

GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir("src/main/java") // Set output directory
.setFileOverride(true) // Allow overwriting existing files
.setOpen(false) // Do not automatically open output directory
.setEnableCache(true) // Add secondary cache configuration in XML
.setAuthor("Your Name") // Set developer name
.setKotlin(false) // Disable Kotlin mode
.setSwagger2(true) // Enable Swagger2 mode
.setActiveRecord(false) // Disable ActiveRecord mode
.setBaseResultMap(true) // Enable BaseResultMap
.setBaseColumnList(true) // Enable baseColumnList
.setDateType(DateType.TIME_PACK) // Set time type strategy
.setEntityName("%sEntity") // Set entity naming convention
.setMapperName("%sDao") // Set Mapper naming convention
.setXmlName("%sDao") // Set Mapper XML naming convention
.setServiceName("%sService") // Set Service naming convention
.setServiceImplName("%sServiceImpl") // Set Service impl naming convention
.setControllerName("%sController") // Set Controller naming convention
.setIdType(IdType.AUTO); // Set primary key ID type to auto-increment

In this example, we have configured global strategies, specifying the output directory, file overwrite settings, developer information, etc., and set various naming conventions and primary key ID types. These configurations will affect the structure and content of the generated code.

Adjust these configuration parameters according to your project requirements and preferences to ensure the generated code meets your expectations. For example, if you want entity class names to end with Entity, you can set entityName to %sEntity. If you want secondary cache configurations included in the generated XML files, set enableCache to true.

Injection Configuration (injectionConfig) Explained

Injection configuration allows developers to customize the behavior of the code generator, including custom return configurations, custom output files, and custom file creation logic. These configurations provide flexibility, enabling the code generator to adapt to more complex project requirements.

map

  • Description: Customizes the return configuration Map object, which can be passed to the template engine and referenced via cfg.xxx.
  • Purpose: Used to access custom configuration information in templates.

fileOutConfigList

  • Description: Customize output files by configuring FileOutConfig to specify template files and output files, enabling custom file generation.
  • Purpose: Used to generate non-standard format files or create files in specific directories.

fileCreate

  • Description: Customize whether to create a file by implementing the IFileCreate interface.
  • Purpose: Used to determine whether a class needs to be overwritten during creation or to implement the file diff algorithm merge.

initMap

  • Description: Injects a custom Map object. Note that it needs to be placed using the setMap method.
  • Purpose: Used to inject additional configuration information in the code generator.

Example Configuration

InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
// Custom Map object, which can be referenced in templates via cfg.xxx
this.setMap(new HashMap<String, Object>() {{
put("author", "Your Name");
put("project", "MyBatis-Plus Code Generator");
}});
}
@Override
public FileOutConfig getFileOutConfig(TableInfo tableInfo) {
// Custom output file configuration
return new FileOutConfig(tableInfo.getEntityName()) {
@Override
public String outputFile(TableInfo tableInfo) {
// Custom output file path
return "src/main/java/" + tableInfo.getEntityName() + ".java";
}
};
}
@Override
public IFileCreate getFileCreate() {
// Custom file creation logic
return new IFileCreate() {
@Override
public boolean isCreate(File file) {
// Custom logic to determine whether to create the file
return !file.exists() || file.length() == 0;
}
};
}
};

In this example, we have configured injection settings, including a custom Map object, custom output file configuration, and custom file creation logic.

  • In the initMap method, we created a Map object containing author and project name, which can be referenced in templates via cfg.xxx.
  • In the getFileOutConfig method, we returned a custom FileOutConfig object specifying the output file path.
  • In the getFileCreate method, we returned a custom IFileCreate implementation to determine whether a file needs to be created.

Adjust these configuration parameters according to your project requirements to ensure the generated code meets your expectations. For example:

  • If you need to access additional configuration information in templates, add these details in the initMap method.
  • If you need to generate files in a specific format, specify the corresponding template and output path in the getFileOutConfig method.
  • If you require custom file creation logic, implement the corresponding decision logic in the getFileCreate method.
Baomidou

© 2016-2025 Baomidou™. All Rights Reserved.

Power by Astro Starlight | Sponsored by JetBrains

渝ICP备2021000141号-1 | 渝公网安备50011302222097