Mybatis Plus最新程式碼生成器AutoGenerator,更簡單更高效!
theme: channing-cyan highlight: dracula
開啟掘金成長之旅!這是我參與「掘金日新計劃 · 2 月更文挑戰」的第 8 天,點選檢視活動詳情
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
今天的主角是MP推出的一款程式碼生成器,本文主要來介紹一下它強大的程式碼生成功能。
一、概述
AutoGenerator
是 MyBatis Plus
推出的程式碼生成器,可以快速生成Entity
、Mapper
、Mapper XML
、Service
、Controller
等各個模組的程式碼,比Mybatis Generator
更強大,開發效率更高。
以往我們使用mybatis generator
生成程式碼正常需要配置mybatis-generator-config.xml
,程式碼配置比較繁瑣複雜,比如:
```
<!-- 註釋 -->
<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 需要設定 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 型別轉換 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>
<!-- 生成實體類地址 -->
<javaModelGenerator targetPackage="com.codingmore.mbg.po" targetProject="src/main/java">
<!-- 是否針對string型別的欄位在set方法中進行修剪,預設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>
```
二、使用AutoGenerator
1. 初始化資料庫表結構(以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 '手機號',
create_by
varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '建立人',
create_time
datetime(0) NULL DEFAULT NULL COMMENT '建立時間',
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(預設)、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) { // 資料來源配置 FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin") .globalConfig(builder -> { builder.author("austin") // 設定作者 .enableSwagger() // 開啟 swagger 模式 預設值:false .disableOpenDir() // 禁止開啟輸出目錄 預設值:true .commentDate("yyyy-MM-dd") // 註釋日期 .dateType(DateType.ONLY_DATE) //定義生成的實體類中日期型別 DateType.ONLY_DATE 預設值: DateType.TIME_PACK .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定輸出目錄 })
.packageConfig(builder -> {
builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模組名
.controller("controller") //Controller 包名 預設值:controller
.entity("entity") //Entity 包名 預設值:entity
.service("service") //Service 包名 預設值:service
.mapper("mapper") //Mapper 包名 預設值:mapper
.other("model")
//.moduleName("xxx") // 設定父包模組名 預設值:無
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 設定mapperXml生成路徑
//預設存放在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") // 設定需要生成的表名 可邊長引數“user”, “user1”
.addTablePrefix("tb_", "gms_") // 設定過濾表字首
.serviceBuilder()//service策略配置
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()// 實體類策略配置
.idType(IdType.ASSIGN_ID)//主鍵策略 雪花演算法自動生成的id
.addTableFills(new Column("create_time", FieldFill.INSERT)) // 自動填充配置
.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
.enableLombok() //開啟lombok
.logicDeleteColumnName("deleted")// 說明邏輯刪除是哪個欄位
.enableTableFieldAnnotation()// 屬性加上註解說明
.controllerBuilder() //controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 開啟RestController註解
.mapperBuilder()// mapper策略配置
.formatMapperFileName("%sMapper")
.enableMapperAnnotation()//@mapper註解開啟
.formatXmlFileName("%sMapper");
})
// 使用Freemarker引擎模板,預設的是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);
});
}
} ```
未生成程式碼前的專案目錄如下:
執行CodeGenerator
生成程式碼:
14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================準備生成檔案...==========================
14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執行SQL:show table status WHERE 1=1 AND NAME IN ('user')
14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數:1,耗時(ms):26
14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執行SQL:show full fields from `user`
14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 當前表[user]的主鍵為自增主鍵,會導致全域性主鍵的ID型別設定失效!
14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數:5,耗時(ms):14
14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================檔案生成完成!!!==========================
專案成功生成了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;
/* *
* 使用者 *
* * @author austin * @since 2023-02-09 / @Getter @Setter @TableName("user") @ApiModel(value = "User物件", 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("手機號")
@TableField("mobile")
private String mobile;
@ApiModelProperty("建立人")
@TableField("create_by")
private String createBy;
@ApiModelProperty("建立時間")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
} ```
想了解MyBatis Plus程式碼生成配置可以參考官方配置:程式碼生成器配置新
總結
對比Mybatis
的Generator
和MyBatis-Plus
的AutoGenerator
,就可以得出這樣一條結論:後者的配置更簡單,開發效率也更高,功能也更強大——可快速生成Mapper
、Model
、Service
、Controller
、DTO/VO
層程式碼,到這裡AutoGenerator生成器的介紹已經完成,文章如果對你有所幫助,歡迎點贊👍+關注❤+收藏✔,我是👨🎓austin流川楓,我們下期見!