更簡單更高效的Mybatis?Plus最新代碼生成器AutoGenerator
正文
MyBatis-Plus(簡稱 MP)是一個(gè) MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生。
今天的主角是MP推出的一款代碼生成器,本文主要來介紹一下它強(qiáng)大的代碼生成功能。
一、概述
AutoGenerator 是 MyBatis Plus推出的代碼生成器,可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各個(gè)模塊的代碼,比Mybatis Generator更強(qiáng)大,開發(fā)效率更高。

以往我們使用mybatis generator生成代碼正常需要配置mybatis-generator-config.xml,代碼配置比較繁瑣復(fù)雜,比如:
<generatorConfiguration>
<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 注釋 -->
<commentGenerator>
<!-- 是否不生成注釋 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- jdbc連接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://ip:3306/codingmoretiny02?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false"
userId="codingmoretiny02"
password="123456">
<!--高版本的 mysql-connector-java 需要設(shè)置 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 類型轉(zhuǎn)換 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>
<!-- 生成實(shí)體類地址 -->
<javaModelGenerator targetPackage="com.codingmore.mbg.po" targetProject="src/main/java">
<!-- 是否針對(duì)string類型的字段在set方法中進(jìn)行修剪,默認(rèn)false -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成Mapper.xml文件 -->
<sqlMapGenerator targetPackage="com.codingmore.mbg.mapper" targetProject="src/main/resources">
</sqlMapGenerator>
<!-- 生成 XxxMapper.java 接口-->
<javaClientGenerator targetPackage="com.codingmore.mbg.dao" targetProject="src/main/java" type="XMLMAPPER">
</javaClientGenerator>
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
二、使用AutoGenerator
1. 初始化數(shù)據(jù)庫表結(jié)構(gòu)(以User用戶表為例)
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用戶名', `mobile` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手機(jī)號(hào)', `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '創(chuàng)建人', `create_time` datetime(0) NULL DEFAULT NULL COMMENT '創(chuàng)建時(shí)間', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `username`(`username`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
2. 在 pom.xml 文件中添加 AutoGenerator 的依賴。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
3. 添加模板引擎依賴
MyBatis-Plus 支持 Velocity(默認(rèn))、Freemarker、Beetl,這里使用Freemarker引擎。
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
4. 全局配置
package com.shardingspherejdbc.mybatisplus.genertor;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 代碼生成器
*
* @author: austin
* @since: 2023/2/6 15:28
*/
public class CodeGenerator {
public static void main(String[] args) {
// 數(shù)據(jù)源配置
FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin")
.globalConfig(builder -> {
builder.author("austin") // 設(shè)置作者
.enableSwagger() // 開啟 swagger 模式 默認(rèn)值:false
.disableOpenDir() // 禁止打開輸出目錄 默認(rèn)值:true
.commentDate("yyyy-MM-dd") // 注釋日期
.dateType(DateType.ONLY_DATE) //定義生成的實(shí)體類中日期類型 DateType.ONLY_DATE 默認(rèn)值: DateType.TIME_PACK
.outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定輸出目錄
})
.packageConfig(builder -> {
builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模塊名
.controller("controller") //Controller 包名 默認(rèn)值:controller
.entity("entity") //Entity 包名 默認(rèn)值:entity
.service("service") //Service 包名 默認(rèn)值:service
.mapper("mapper") //Mapper 包名 默認(rèn)值:mapper
.other("model")
//.moduleName("xxx") // 設(shè)置父包模塊名 默認(rèn)值:無
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 設(shè)置mapperXml生成路徑
//默認(rèn)存放在mapper的xml下
})
.injectionConfig(consumer -> {
Map<String, String> customFile = new HashMap<>();
// DTO、VO
customFile.put("DTO.java", "/templates/entityDTO.java.ftl");
customFile.put("VO.java", "/templates/entityVO.java.ftl");
consumer.customFile(customFile);
})
.strategyConfig(builder -> {
builder.addInclude("user") // 設(shè)置需要生成的表名 可邊長參數(shù)“user”, “user1”
.addTablePrefix("tb_", "gms_") // 設(shè)置過濾表前綴
.serviceBuilder()//service策略配置
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()// 實(shí)體類策略配置
.idType(IdType.ASSIGN_ID)//主鍵策略 雪花算法自動(dòng)生成的id
.addTableFills(new Column("create_time", FieldFill.INSERT)) // 自動(dòng)填充配置
.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
.enableLombok() //開啟lombok
.logicDeleteColumnName("deleted")// 說明邏輯刪除是哪個(gè)字段
.enableTableFieldAnnotation()// 屬性加上注解說明
.controllerBuilder() //controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 開啟RestController注解
.mapperBuilder()// mapper策略配置
.formatMapperFileName("%sMapper")
.enableMapperAnnotation()//@mapper注解開啟
.formatXmlFileName("%sMapper");
})
// 使用Freemarker引擎模板,默認(rèn)的是Velocity引擎模板
//.templateEngine(new FreemarkerTemplateEngine())
.templateEngine(new EnhanceFreemarkerTemplateEngine())
.execute();
}
}
5. 自定義模板生成DTO、VO
package com.shardingspherejdbc.mybatisplus.engine;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Map;
/**
* 代碼生成器支持自定義[DTO\VO等]模版
*
* @author: austin
* @since: 2023/2/9 13:00
*/
@Component
public class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine {
@Override
protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
String entityName = tableInfo.getEntityName();
String otherPath = this.getPathInfo(OutputFile.other);
customFile.forEach((key, value) -> {
String fileName = String.format(otherPath + File.separator + entityName + "%s", key);
this.outputFile(new File(fileName), objectMap, value, true);
});
}
}
未生成代碼前的項(xiàng)目目錄如下:

運(yùn)行CodeGenerator生成代碼:
14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================準(zhǔn)備生成文件...==========================
14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執(zhí)行SQL:show table status WHERE 1=1 AND NAME IN ('user')
14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數(shù):1,耗時(shí)(ms):26
14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執(zhí)行SQL:show full fields from `user`
14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 當(dāng)前表[user]的主鍵為自增主鍵,會(huì)導(dǎo)致全局主鍵的ID類型設(shè)置失效!
14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數(shù):5,耗時(shí)(ms):14
14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成?。?!==========================
項(xiàng)目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。

User用戶類
package com.shardingspherejdbc.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 用戶
* </p>
*
* @author austin
* @since 2023-02-09
*/
@Getter
@Setter
@TableName("user")
@ApiModel(value = "User對(duì)象", description = "用戶")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("用戶名")
@TableField("username")
private String username;
@ApiModelProperty("手機(jī)號(hào)")
@TableField("mobile")
private String mobile;
@ApiModelProperty("創(chuàng)建人")
@TableField("create_by")
private String createBy;
@ApiModelProperty("創(chuàng)建時(shí)間")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
}
想了解MyBatis Plus代碼生成配置可以參考官方配置:代碼生成器配置新
總結(jié)
對(duì)比Mybatis的Generator和MyBatis-Plus的AutoGenerator,就可以得出這樣一條結(jié)論:后者的配置更簡單,開發(fā)效率也更高,功能也更強(qiáng)大——可快速生成Mapper、Model、Service、Controller、DTO/VO層代碼,到這里AutoGenerator生成器的介紹已經(jīng)完成
以上就是更簡單更高效的Mybatis Plus最新代碼生成器AutoGenerator的詳細(xì)內(nèi)容,更多關(guān)于Mybatis Plus代碼生成器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
淺析Spring Boot單體應(yīng)用熔斷技術(shù)的使用
這篇文章主要介紹了淺析Spring Boot單體應(yīng)用熔斷技術(shù)的使用,幫助大家更好的理解和使用spirngboot框架,感興趣的朋友可以了解下2021-01-01
Resttemplate中設(shè)置超時(shí)時(shí)長方式
這篇文章主要介紹了Resttemplate中設(shè)置超時(shí)時(shí)長方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Java編程實(shí)現(xiàn)游戲中的簡單碰撞檢測(cè)功能示例
這篇文章主要介紹了Java編程中的簡單碰撞檢測(cè)功能,涉及java針對(duì)坐標(biāo)點(diǎn)的相關(guān)數(shù)學(xué)運(yùn)算操作技巧,需要的朋友可以參考下2017-10-10
Java web基礎(chǔ)學(xué)習(xí)之開發(fā)環(huán)境篇(詳解)
下面小編就為大家?guī)硪黄狫ava web基礎(chǔ)學(xué)習(xí)之開發(fā)環(huán)境篇(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
SpringCloud如何利用Feign訪問外部http請(qǐng)求
這篇文章主要介紹了SpringCloud如何利用Feign訪問外部http請(qǐng)求,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
淺談MultipartFile中transferTo方法的坑
這篇文章主要介紹了MultipartFile中transferTo方法的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
java設(shè)計(jì)模式之單例模式的詳解及優(yōu)點(diǎn)
這篇文章主要介紹了java設(shè)計(jì)模式之單例模式的詳解及優(yōu)點(diǎn)的相關(guān)資料,如果一個(gè)類始終只能創(chuàng)建一個(gè)實(shí)例,那么這個(gè)類被稱為單例類,這種設(shè)計(jì)模式被稱為單例模式,需要的朋友可以參考下2017-08-08

