当前位置:   article > 正文

Mybatis Plus最新代码生成器AutoGenerator,更简单更高效!_fastautogenerator

fastautogenerator

一、概述

AutoGenerator 是 MyBatis Plus推出的代码生成器,可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,比Mybatis Generator更强大,开发效率更高。

以往我们使用mybatis generator生成代码正常需要配置mybatis-generator-config.xml,代码配置比较繁琐复杂,比如:

<generatorConfiguration><contextid="myContext"targetRuntime="MyBatis3"defaultModelType="flat"><!-- 注释 --><commentGenerator><!-- 是否不生成注释 --><propertyname="suppressAllComments"value="true"/></commentGenerator><!-- jdbc连接 --><jdbcConnectiondriverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://ip:3306/codingmoretiny02?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"userId="codingmoretiny02"password="123456"><!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true--><propertyname="nullCatalogMeansCurrent"value="true"/></jdbcConnection><!-- 类型转换 --><javaTypeResolver><propertyname="forceBigDecimals"value="true"/></javaTypeResolver><!-- 生成实体类地址 --><javaModelGeneratortargetPackage="com.codingmore.mbg.po"targetProject="src/main/java"><!-- 是否针对string类型的字段在set方法中进行修剪,默认false --><propertyname="trimStrings"value="true"/></javaModelGenerator><!-- 生成Mapper.xml文件 --><sqlMapGeneratortargetPackage="com.codingmore.mbg.mapper"targetProject="src/main/resources"></sqlMapGenerator><!-- 生成 XxxMapper.java 接口--><javaClientGeneratortargetPackage="com.codingmore.mbg.dao"targetProject="src/main/java"type="XMLMAPPER"></javaClientGenerator><tableschema=""tableName="user"domainObjectName="User"enableCountByExample="false"enableDeleteByExample="false"enableSelectByExample="false"enableUpdateByExample="false"selectByExampleQueryId="false"></table></context></generatorConfiguration>复制代码

二、使用AutoGenerator

1. 初始化数据库表结构(以User用户表为例)

  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS =0;
  3. -- ------------------------------ Table structure for user-- ----------------------------DROPTABLE IF EXISTS `user`;
  4. CREATETABLE `user` (
  5. `id` bigint(20) NOTNULL AUTO_INCREMENT,
  6. `username` varchar(50) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NOTNULL COMMENT '用户名',
  7. `mobile` varchar(100) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NULLDEFAULTNULL COMMENT '手机号',
  8. `create_by` varchar(64) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NULLDEFAULTNULL COMMENT '创建人',
  9. `create_time` datetime(0) NULLDEFAULTNULL COMMENT '创建时间',
  10. PRIMARY KEY (`id`) USING BTREE,
  11. UNIQUE INDEX `username`(`username`) USING BTREE
  12. ) ENGINE = InnoDB AUTO_INCREMENT =2CHARACTERSET= utf8mb4 COLLATE= utf8mb4_general_ci COMMENT ='用户' ROW_FORMAT =Dynamic;
  13. SET FOREIGN_KEY_CHECKS =1;
  14. 复制代码

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. 全局配置

  1. package com.shardingspherejdbc.mybatisplus.genertor;
  2. import com.baomidou.mybatisplus.annotation.FieldFill;
  3. import com.baomidou.mybatisplus.annotation.IdType;
  4. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
  5. import com.baomidou.mybatisplus.generator.config.OutputFile;
  6. import com.baomidou.mybatisplus.generator.config.rules.DateType;
  7. import com.baomidou.mybatisplus.generator.fill.Column;
  8. import com.baomidou.mybatisplus.generator.fill.Property;
  9. import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine;
  10. import java.util.Collections;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. /**
  14. * 代码生成器
  15. *
  16. * @author: austin
  17. * @since: 2023/2/6 15:28
  18. */publicclassCodeGenerator {
  19. publicstaticvoidmain(String[] args) {
  20. // 数据源配置
  21. FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin")
  22. .globalConfig(builder -> {
  23. builder.author("austin") // 设置作者
  24. .enableSwagger() // 开启 swagger 模式 默认值:false
  25. .disableOpenDir() // 禁止打开输出目录 默认值:true
  26. .commentDate("yyyy-MM-dd") // 注释日期
  27. .dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
  28. .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录
  29. })
  30. .packageConfig(builder -> {
  31. builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模块名
  32. .controller("controller") //Controller 包名 默认值:controller
  33. .entity("entity") //Entity 包名 默认值:entity
  34. .service("service") //Service 包名 默认值:service
  35. .mapper("mapper") //Mapper 包名 默认值:mapper
  36. .other("model")
  37. //.moduleName("xxx") // 设置父包模块名 默认值:无
  38. .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径//默认存放在mapper的xml下
  39. })
  40. .injectionConfig(consumer -> {
  41. Map<String, String> customFile = newHashMap<>();
  42. // DTO、VO
  43. customFile.put("DTO.java", "/templates/entityDTO.java.ftl");
  44. customFile.put("VO.java", "/templates/entityVO.java.ftl");
  45. consumer.customFile(customFile);
  46. })
  47. .strategyConfig(builder -> {
  48. builder.addInclude("user") // 设置需要生成的表名 可边长参数“user”, “user1”
  49. .addTablePrefix("tb_", "gms_") // 设置过滤表前缀
  50. .serviceBuilder()//service策略配置
  51. .formatServiceFileName("%sService")
  52. .formatServiceImplFileName("%sServiceImpl")
  53. .entityBuilder()// 实体类策略配置
  54. .idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id
  55. .addTableFills(newColumn("create_time", FieldFill.INSERT)) // 自动填充配置
  56. .addTableFills(newProperty("update_time", FieldFill.INSERT_UPDATE))
  57. .enableLombok() //开启lombok
  58. .logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段
  59. .enableTableFieldAnnotation()// 属性加上注解说明
  60. .controllerBuilder() //controller 策略配置
  61. .formatFileName("%sController")
  62. .enableRestStyle() // 开启RestController注解
  63. .mapperBuilder()// mapper策略配置
  64. .formatMapperFileName("%sMapper")
  65. .enableMapperAnnotation()//@mapper注解开启
  66. .formatXmlFileName("%sMapper");
  67. })
  68. // 使用Freemarker引擎模板,默认的是Velocity引擎模板//.templateEngine(new FreemarkerTemplateEngine())
  69. .templateEngine(newEnhanceFreemarkerTemplateEngine())
  70. .execute();
  71. }
  72. }
  73. 复制代码

5. 自定义模板生成DTO、VO

  1. package com.shardingspherejdbc.mybatisplus.engine;
  2. import com.baomidou.mybatisplus.generator.config.OutputFile;
  3. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  4. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  5. import org.springframework.stereotype.Component;
  6. import java.io.File;
  7. import java.util.Map;
  8. /**
  9. * 代码生成器支持自定义[DTO\VO等]模版
  10. *
  11. * @author: austin
  12. * @since: 2023/2/9 13:00
  13. */@ComponentpublicclassEnhanceFreemarkerTemplateEngineextendsFreemarkerTemplateEngine {
  14. @OverrideprotectedvoidoutputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
  15. String entityName = tableInfo.getEntityName();
  16. String otherPath = this.getPathInfo(OutputFile.other);
  17. customFile.forEach((key, value) -> {
  18. String fileName = String.format(otherPath + File.separator + entityName + "%s", key);
  19. this.outputFile(newFile(fileName), objectMap, value, true);
  20. });
  21. }
  22. }
  23. 复制代码

未生成代码前的项目目录如下:

运行CodeGenerator生成代码:

  1. 14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
  2. 14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show table status WHERE 1=1 AND NAME IN ('user')
  3. 14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:1,耗时(ms):26
  4. 14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `user`
  5. 14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[user]的主键为自增主键,会导致全局主键的ID类型设置失效!
  6. 14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:5,耗时(ms):14
  7. 14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================
  8. 复制代码

项目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。

User用户类

  1. package com.shardingspherejdbc.mybatisplus.entity;
  2. import com.baomidou.mybatisplus.annotation.FieldFill;
  3. import com.baomidou.mybatisplus.annotation.IdType;
  4. import com.baomidou.mybatisplus.annotation.TableField;
  5. import com.baomidou.mybatisplus.annotation.TableId;
  6. import com.baomidou.mybatisplus.annotation.TableName;
  7. import io.swagger.annotations.ApiModel;
  8. import io.swagger.annotations.ApiModelProperty;
  9. import lombok.Getter;
  10. import lombok.Setter;
  11. import java.io.Serializable;
  12. import java.util.Date;
  13. /**
  14. * <p>
  15. * 用户
  16. * </p>
  17. *
  18. * @author austin
  19. * @since 2023-02-09
  20. */@Getter@Setter@TableName("user")@ApiModel(value = "User对象", description = "用户")publicclassUserimplementsSerializable {
  21. private static final long serialVersionUID = 1L;
  22. @TableId(value = "id", type = IdType.AUTO)privateLong id;
  23. @ApiModelProperty("用户名")@TableField("username")private String username;
  24. @ApiModelProperty("手机号")@TableField("mobile")private String mobile;
  25. @ApiModelProperty("创建人")@TableField("create_by")private String createBy;
  26. @ApiModelProperty("创建时间")@TableField(value = "create_time", fill = FieldFill.INSERT)private Date createTime;
  27. }
  28. 复制代码
想了解MyBatis Plus代码生成配置可以参考官方配置: 代码生成器配置新

作者:austin流川枫

链接:https://juejin.cn/post/7198039436037570615

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/231156?site
推荐阅读
相关标签
  

闽ICP备14008679号