Code Generator
The brand new MyBatis-Plus code generator allows you to quickly generate the code you want through the builder pattern. It’s fast and elegant. Take a look at the code below to see it in action.
FastAutoGenerator.create("url", "username", "password") .globalConfig(builder -> builder .author("Baomidou") .outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java") .commentDate("yyyy-MM-dd") ) .packageConfig(builder -> builder .parent("com.baomidou.mybatisplus") .entity("entity") .mapper("mapper") .service("service") .serviceImpl("service.impl") .xml("mapper.xml") ) .strategyConfig(builder -> builder .entityBuilder() .enableLombok() ) .templateEngine(new FreemarkerTemplateEngine()) .execute();
Installation
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.14</version></dependency>
implementation 'com.baomidou:mybatis-plus-generator:3.5.14'
Since the code generator uses a template engine, please introduce your preferred template engine yourself. MyBatis-Plus Generator supports the following template engines:
- VelocityTemplateEngine(Default)
- FreemarkerTemplateEngine
- BeetlTemplateEngine
- EnjoyTemplateEngine
If you want to use or adapt other template engines, you can extend AbstractTemplateEngine
yourself and implement customizations by referring to other template engine implementations.
Generation Methods
The code generator currently supports two generation methods:
-
DefaultQuery (Metadata Query)
- Advantages: Reads database metadata information based on common interfaces, offering good database generality.
- Disadvantages: Relies on database vendor driver implementations.
- Note: This is the default method. Some type handling might not be ideal.
-
SQLQuery (SQL Query)
- Advantages: Requires writing corresponding queries for tables, primary keys, fields, etc., specific to the database.
- Disadvantages: Not very generic; compatibility issues might exist between different versions of the same database vendor (e.g., H2 database only supports version 1.X).
- Note: Will not be maintained in the future.
If you are using a known database (without version compatibility issues), you can continue using the original SQL query method. Example code is as follows:
// MYSQL Example: Switch to SQL query mode, requires specifying dbQuery and typeConvert for generationFastAutoGenerator.create("url", "username", "password") .dataSourceConfig(builder -> builder.databaseQueryClass(SQLQuery.class) .typeConvert(new MySqlTypeConvert()) .dbQuery(new MySqlQuery()) ) // Other Config ...
The metadata query currently has the following issues:
- Does not support generating tables in reverse using the NotLike method.
- Unable to read table comments. Solutions:
- Add properties
remarks=true&useInformationSchema=true
to the MySQL connection string. - Add property
remarks=true
orremarksReporting=true
(for some driver versions) to the Oracle connection string. - SqlServer: Not supported by the driver.
- Add properties
- Suboptimal handling of some PostgreSQL types (e.g., json, jsonb, uuid, xml, money types). Solutions:
- Convert them to custom types and handle them with a custom TypeHandler.
- Extend the typeConvertHandler to handle them (typeName acquisition was added in version 3.5.3.3).
- MySQL tinyint field conversion issues:
-
When the field length is 1, it cannot be converted to a Boolean field. It is recommended to add
&tinyInt1isBit=true
when specifying the database connection. -
When the field length is greater than 1, it defaults to Byte. If you want to convert it to Integer, you can use the following code:
FastAutoGenerator.create("url", "username", "password").dataSourceConfig(builder ->builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {// Compatible with older versions converting to Integerif (JdbcType.TINYINT == metaInfo.getJdbcType()) {return DbColumnType.INTEGER;}return typeRegistry.getColumnType(metaInfo);}));
-
Usage
You can use the code generator in the following two ways.
Quick Generation
Add the generator code directly to the main method in CodeGenerator, configure it accordingly, and then run it directly to generate the code.
public static void main(String[] args) { FastAutoGenerator.create("url", "username", "password") .globalConfig(builder -> { builder.author("baomidou") // Set author .enableSwagger() // Enable swagger mode .outputDir("D://"); // Specify output directory }) .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> { int typeCode = metaInfo.getJdbcType().TYPE_CODE; if (typeCode == Types.SMALLINT) { // Custom type conversion return DbColumnType.INTEGER; } return typeRegistry.getColumnType(metaInfo); }) ) .packageConfig(builder -> builder.parent("com.baomidou.mybatisplus.samples.generator") // Set parent package name .moduleName("system") // Set parent package module name .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")) // Set mapperXml generation path ) .strategyConfig(builder -> builder.addInclude("t_simple") // Set table names to generate .addTablePrefix("t_", "c_") // Set filter table prefixes ) .templateEngine(new FreemarkerTemplateEngine()) // Use Freemarker engine template, default is Velocity engine template .execute();}
Interactive Generation
In interactive generation, after running, you will be prompted to input the corresponding content. Once the configuration input is complete, the relevant code will be automatically generated.
public static void main(String[] args) { FastAutoGenerator.create("url", "username", "password") // Global configuration .globalConfig((scanner, builder) -> builder.author(scanner.apply("Please enter the author name?"))) // Package configuration .packageConfig((scanner, builder) -> builder.parent(scanner.apply("Please enter the package name?"))) // Strategy configuration .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("Please enter the table names, separated by commas? Enter 'all' for all tables"))) .entityBuilder() .enableLombok() .addTableFills( new Column("create_time", FieldFill.INSERT) ) .build()) // Use Freemarker engine template, default is Velocity engine template .templateEngine(new FreemarkerTemplateEngine()) .execute();}
// Handle 'all' caseprotected static List<String> getTables(String tables) { return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));}
If you need more examples, please check the samples in the test package.
Configuration
Please proceed to Code Generator Configuration for details.
Resources
- 👉 Source Code: Welcome to read the source code and contribute.
- 👉 Video Tutorial Details: Welcome to follow, like, coin, and comment.