更簡單更高效的代碼生成器AutoGenerator
MyBatis-Plus(簡稱 MP)是一個?MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生。
今天的主角是MP推出的一款代碼生成器,本文主要來介紹一下它強(qiáng)大的代碼生成功能。
一、概述
AutoGenerator
是 MyBatis Plus
推出的代碼生成器,可以快速生成Entity
、Mapper
、Mapper XML
、Service
、Controller
等各個模塊的代碼,比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"> <!-- 是否針對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ī)號', `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)建時間', 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)//主鍵策略 雪花算法自動生成的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引擎模板,默認(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,耗時(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]的主鍵為自增主鍵,會導(dǎo)致全局主鍵的ID類型設(shè)置失效! 14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數(shù):5,耗時(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對象", 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ī)號") @TableField("mobile") private String mobile; @ApiModelProperty("創(chuàng)建人") @TableField("create_by") private String createBy; @ApiModelProperty("創(chuàng)建時間") @TableField(value = "create_time", fill = FieldFill.INSERT) private Date createTime; }
想了解MyBatis Plus代碼生成配置可以參考官方配置:代碼生成器配置新
總結(jié)
對比Mybatis
的Generator
和MyBatis-Plus
的AutoGenerator
,就可以得出這樣一條結(jié)論:后者的配置更簡單,開發(fā)效率也更高,功能也更強(qiáng)大——可快速生成Mapper
、Model
、Service
、Controller
、DTO/VO
層代碼,到這里AutoGenerator生成器的介紹已經(jīng)完成,文章如果對你有所幫助,歡迎點(diǎn)贊??+關(guān)注?+收藏?