Code Generator Configuration
The MyBatis-Plus code generator is a powerful tool that automatically generates corresponding entity classes, Mapper interfaces, XML mapping files, and Service layer code based on your database table structure. This tool significantly simplifies development workflows based on the MyBatis framework and improves development efficiency, especially when you need to work with numerous database tables.
Key Features
- Automation: The code generator automatically creates corresponding Java code based on your database table structure, reducing the manual effort of writing repetitive code.
- Configurability: You can flexibly specify package paths, table names, field names, templates, and other settings for the generated code through configuration files or code, meeting the needs of different projects.
- Template Support: Supports custom code templates, allowing you to tailor the code style and structure according to your project requirements.
- Multi-Database Support: Works with multiple database types such as MySQL, Oracle, and SQL Server. You only need to configure the corresponding database connection information.
- Easy Integration: Easily integrates into existing projects. You can start the code generation process with just a few lines of code.
Use Cases
- New Project Setup: When starting a new project, you can use the code generator to quickly create basic CRUD code, accelerating project launch.
- Table Structure Changes: When your database table structure changes, you can use the code generator to update the corresponding Java code, maintaining consistency between your code and database.
- Repetitive Tasks: In scenarios requiring extensive similar CRUD operations, the code generator can significantly reduce repetitive work and improve development efficiency.
How to Use
- Configure Data Source: Specify the database type, connection URL, username, and password.
- Configure Strategy: Select the tables for which you want to generate code, and set naming strategies for table names and column names.
- Configure Package Information: Set the package path for the generated code, including entity classes, Mapper interfaces, Services, and more.
- Configure Templates: If you need to customize the code style, you can configure or create custom code templates.
- Execute Generation: Run the code generator to produce the corresponding Java code based on your configuration.
Example 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 name .setOpen(false) // Set whether to open the directory after generation .setFileOverride(true) // Set whether to overwrite existing files .setServiceName("%sService") // Set Service interface name suffix .setIdType(IdType.AUTO) // Set primary key generation strategy .setSwagger2(true); // Set whether to generate Swagger annotations
// Data source configuration DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL) // Set 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") // Specify table names to generate code for .setNaming(NamingStrategy.underline_to_camel) // Set table name to class name conversion strategy .setColumnNaming(NamingStrategy.underline_to_camel) // Set column name to property name conversion strategy .setEntityLombokModel(true) // Set entity class to use Lombok model .setRestControllerStyle(true) // Set Controller to use REST style .setTablePrefix(new String[]{"tbl_"}); // Set table name prefixes
// Package configuration PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent("com.example") // Set parent package name .setMapper("mapper") // Set sub-package name for Mapper interfaces .setEntity("entity") // Set sub-package name for entity classes .setController("controller") // Set sub-package name for Controller classes .setService("service") // Set sub-package name for Service classes .setXml("mapper"); // Set sub-package name for Mapper XML files
// Template 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
// Combine 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, you can focus more on implementing business logic rather than writing repetitive CRUD code, which improves development efficiency and code quality.
Basic Configuration
Data Source Configuration (dataSource)
- Type:
DataSourceConfig
- Default:
null
The data source configuration specifies 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 the corresponding code.
Example Configuration:
DataSourceConfig dataSourceConfig = new DataSourceConfig();dataSourceConfig.setDbType(DbType.MYSQL) // Set the 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 value:
null
The database table configuration specifies which tables to generate code for or which tables to exclude. Using 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); // Use REST style for Controller
Package Name Configuration (packageInfo)
- Type:
PackageConfig
- Default:
null
Package name configuration is used to specify the package path for the 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 the parent package name .setMapper("mapper") // Set the sub-package name for Mapper interfaces .setEntity("entity") // Set the sub-package name for entity classes .setController("controller"); // Set the sub-package name for Controller classes
Template Configuration (template)
- Type:
TemplateConfig
- Default:
null
Template configuration allows you to customize the templates used for code generation, enabling personalized operations. Through template configuration, you can customize 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 the Controller template path .setEntity("templates/entity.java.vm") // Set the entity class template path .setMapper("templates/mapper.java.vm"); // Set the Mapper interface template path
Global Strategy Configuration (globalConfig)
- Type:
GlobalConfig
- Default:
null
The global strategy configuration provides global settings such as author information and output paths.
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 you to perform operations like injecting custom parameters to achieve personalized operations. Through injection configuration, you can add additional logic 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 generate code that matches your project structure according to your requirements, significantly improving development efficiency. Remember to adjust configuration parameters based on your actual project needs to achieve optimal code generation results.
Data Source Configuration (dataSource) Explained
The data source configuration is a crucial part of the MyBatis-Plus code generator. It defines how to connect to your database and how to query database information. Below is a detailed explanation and examples for 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 the
dbType
. - Customization: You can implement the
IDbQuery
interface to customize database query SQL statements for returning specific content.
dbType
- Description: Database type, a required configuration option.
- Built-in Support: MyBatis-Plus has built-in support for various common database types, such as MySQL, Oracle, PostgreSQL, and more.
schemaName
- Description: The database schema name, required by certain database systems (such as PostgreSQL).
- Example: In PostgreSQL, you can specify it 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 the
dbType
. - Customization: If the built-in conversion types do not meet your requirements, you can implement the
ITypeConvert
interface to customize the conversion from database field types to Java types, or implement theIColumnType
interface for more advanced customization.
url
- Description: The database connection URL, which contains 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 the database connection, used for authentication.
password
- Description: The password for the 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 configure a data source for a MySQL database. We specify the database type, connection URL, username, password, and driver name. This information is used to establish a connection to the database and retrieve table structure information to generate the corresponding Java code.
Adjust these parameters according to your actual database configuration to ensure they match your database environment.
Database Table Configuration (strategy) Explained
Database table configuration defines 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 properties.
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: Uses underscore to camel case naming.
columnNaming
- Description: The naming strategy for mapping database table columns to entity properties.
- Default Value: When not specified, follows the
naming
strategy.
tablePrefix
- Description: Table prefix used to filter tables that have a specific prefix.
fieldPrefix
- Description: Field prefix, used to filter fields that have a specific prefix.
superEntityClass
- Description: Specifies the fully qualified class name (including package name) for your custom base Entity class.
superEntityColumns
- Description: Custom base Entity class, common fields.
superMapperClass
- Description: The fully qualified name of your custom base Mapper class, including the package name.
superServiceClass
- Description: The fully qualified class name (including package name) of your custom inherited Service class.
superServiceImplClass
- Description: The fully qualified class name, including package name, for your custom inherited ServiceImpl class.
superControllerClass
- Description: The fully qualified class name, including package name, of the custom Controller class you are extending.
enableSqlFilter Since 3.3.1
- Description: Enables SQL fuzzy table name matching by default. When disabled,
likeTable
andnotLikeTable
become ineffective, andinclude
andexclude
will use in-memory filtering instead. - Default:
true
- Note: Set this to
false
manually if you encounter SQL syntax compatibility issues. Known incompatible scenarios include the MyCat middleware. For more information, see ISSUE-2102.
include
- Description: The table names to include. Regular expressions are allowed when
enableSqlFilter
isfalse
.
likeTable Since 3.3.0
-
Description: Performs fuzzy matching on table names. Use this or notLikeTable, but not both.
-
Type:
String
-
Default:
null
// Example: Query all tables starting with 'sys'List<Map<String, Object>> list = mapper.selectList( Wrappers.<Map<String, Object>>query() .likeTable("sys%"));
exclude
- Description: The table names you want to exclude. Regular expressions are allowed when
enableSqlFilter
isfalse
.
notLikeTable Since 3.3.0
- Description: Excludes table names using fuzzy matching. Use this or
likeTable
- choose one to configure.
entityColumnConstant
- Description: Whether to generate field constants for the entity.
- Default Value:
false
entityBuilderModel @Deprecated
- Description: Whether the entity uses the builder pattern.
- Default:
false
- Note: Renamed to chainModel starting from version 3.3.2
chainModel Since 3.3.2
- Description: Whether the [entity] uses the chain model.
- Default value:
false
- Note: Versions below 3.3.2 generated the chain model by default. Starting from version 3.3.2, it is not generated by default. Enable this option if you need it.
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: Generates
@RestController
controllers. - Default value:
false
controllerMappingHyphenStyle
- Description: Convert camelCase to hyphenated style.
- 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 property name for logical deletion.
tableFillList
- Description: Table fill fields.
Example Configuration
StrategyConfig strategyConfig = new StrategyConfig();strategyConfig.setCapitalMode(true) // Use uppercase naming mode .setEntityLombokModel(true) // Use Lombok model .setRestControllerStyle(true) // Generate @RestController controller .setInclude("user", "order") // Include specific tables .setExclude("user_detail") // Exclude specific tables .setEntityBooleanColumnRemoveIsPrefix(true) // Remove 'is' prefix from Boolean fields .setTablePrefix("tbl_") // Set table prefix .setControllerMappingHyphenStyle(true); // Convert camel case to hyphenated style
In this example, we configure a strategy that specifies uppercase naming mode, uses the Lombok model, generates REST-style controllers, and defines which tables to include and exclude. We also set a table prefix and enable hyphenated style for controller mappings.
Adjust these configuration parameters according to your project requirements to ensure the generated code meets your expectations.
Package Name Configuration (packageInfo) Detailed Explanation
Package name configuration defines the package structure for generated code, ensuring that the generated code is placed in the correct directories. By configuring package names, you can control how the code is organized to align with your 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 set, you must specify the full package path for each sub-package name.
moduleName
- Description: The parent package module name, used to distinguish between different modules or subsystems.
entity
- Description: The entity package name, which is the package name where your entity classes are located.
service
- Description: The service package name, which is the package where your service interfaces are located.
serviceImpl
- Description: The service implementation package name, which is the package name where the service implementation classes are located.
mapper
- Description: The Mapper package name, which is the package name where the Mapper interfaces are located.
xml
- Description: The package name for Mapper XML files, which is the package where your Mapper XML files are located.
controller
- Description: The controller package name, which is the package where your controller classes are located.
pathInfo
- Description: Path configuration information used to specify the physical path where the code will be generated.
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 configure a package structure where the parent package name is com.example
, and each subpackage name is set according to its function. 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.
Adjust these configuration parameters according to your project structure and organizational preferences to ensure the generated code integrates properly into your project.
Template Configuration (template) Detailed Explanation
Template configuration allows you to customize the templates used by the code generator to produce code that matches your specific project style and requirements. The MyBatis-Plus code generator supports various types of templates, including entity classes, service classes, Mapper interfaces, XML mapping files, and controller classes.
entity
- Description: Java entity class template used to generate Java entity class code.
entityKt
- Description: Kotlin entity class template, used to generate Kotlin entity class code.
service
- 描述: Service class template used to generate service interface code.
serviceImpl
- Description: Service implementation class template, used to generate service implementation class code.
mapper
- Description: Mapper template used for generating Mapper interface code.
xml
- Description: Mapper XML template used to generate Mapper XML mapping file code.
controller
- 描述: Controller template 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 configure 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 your project, which the code generator will use to generate the corresponding code.
Make sure your template file paths are correct and that the template files follow 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 practice, you may need to adjust the template configuration based on your project’s specific needs. For example, if your project uses Kotlin, you would need to configure the entityKt
template path. If your project doesn’t require certain types of generated code (such as XML mapping files), you can omit the corresponding template configuration.
Global Strategy Configuration (globalConfig) Detailed Explanation
The global strategy configuration provides global settings such as output directory, file overwriting, developer information, and some advanced options like Kotlin mode, Swagger2 integration, and ActiveRecord mode.
outputDir
- Description: The output directory for generated files.
- Default Value:
D drive root directory
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: Developer name.
- 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 types.
- Default Value:
TIME_PACK
entityName
- Description: The naming pattern for entities, where
%s
acts as a placeholder. - Default value:
null
- Example:
%sEntity
generatesUserEntity
mapperName
- Description: Naming pattern for Mapper interfaces, where
%s
acts as a placeholder. - Default Value:
null
- Example:
%sDao
generatesUserDao
xmlName
- Description: Naming pattern for Mapper XML files, where
%s
acts as a placeholder. - Default Value:
null
- Example:
%sDao
generatesUserDao.xml
serviceName
- Description: The naming pattern for Service classes, where
%s
is a placeholder. - Default Value:
null
- Example:
%sBusiness
generatesUserBusiness
serviceImplName
- Description: Naming pattern for Service implementations, where
%s
acts as a placeholder. - Default Value:
null
- Example:
%sBusinessImpl
generatesUserBusinessImpl
controllerName
- Description: The naming pattern for Controllers, where
%s
is a placeholder. - Default Value:
null
- Example:
%sAction
generatesUserAction
idType
- Description: Specifies the ID type for generated primary keys.
- 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) // Don't automatically open output directory .setEnableCache(true) // Add secondary cache configuration in XML .setAuthor("Your Name") // Set developer name .setKotlin(false) // Don't enable Kotlin mode .setSwagger2(true) // Enable Swagger2 mode .setActiveRecord(false) // Don't enable ActiveRecord mode .setBaseResultMap(true) // Enable BaseResultMap .setBaseColumnList(true) // Enable baseColumnList .setDateType(DateType.TIME_PACK) // Set time type strategy .setEntityName("%sEntity") // Set entity naming pattern .setMapperName("%sDao") // Set Mapper naming pattern .setXmlName("%sDao") // Set Mapper XML naming pattern .setServiceName("%sService") // Set Service naming pattern .setServiceImplName("%sServiceImpl") // Set Service impl naming pattern .setControllerName("%sController") // Set Controller naming pattern .setIdType(IdType.AUTO); // Set primary key ID type to auto-increment
In this example, we configure the global strategy by specifying the output directory, file overwrite settings, developer information, and various naming patterns 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 generated entity class names to end with Entity
, you can set entityName
to %sEntity
. If you want generated XML files to include secondary cache configuration, you can set enableCache
to true
.
Injection Configuration (injectionConfig) Detailed Explanation
Injection configuration allows you 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 returned configuration Map object, which can be passed to the template engine and referenced via
cfg.xxx
. - Purpose: Used to access custom configuration information within templates.
fileOutConfigList
- Description: Customize output files by configuring
FileOutConfig
to specify template files and output files, enabling custom file generation. - Purpose: Used for generating files in non-standard formats or for generating files in specific directories.
fileCreate
- Description: Customize whether to create a file by implementing the
IFileCreate
interface. - Purpose: Use this to determine if a specific class should be overwritten during creation, or to implement the file difference algorithm
merge
.
initMap
- Description: Injects a custom Map object. Note that you need to put it in using the
setMap
method. - Purpose: Used to inject additional configuration information into the code generator.
Example Configuration
InjectionConfig injectionConfig = new InjectionConfig() { @Override public void initMap() { // Custom Map object that you can reference in templates using 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 configure the injection settings, including a custom Map object, custom output file configuration, and custom file creation logic.
- In the
initMap
method, we create a Map object containing author and project name information that you can reference in templates usingcfg.xxx
. - In the
getFileOutConfig
method, we return a customFileOutConfig
object that specifies the output file path. - In the
getFileCreate
method, we return a customIFileCreate
implementation used 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 your templates, you can add this information in the initMap
method. If you need to generate files in a specific format, you can specify the corresponding template and output path in the getFileOutConfig
method. If you need custom file creation logic, you can implement the appropriate decision logic in the getFileCreate
method.