Java Mybatis-plus Generator Swagger2

1、先搭建项目,引入依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.9.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <!-- jdbc -->
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-jdbc</artifactId>
  15. </dependency>
  16. <!-- MySQL -->
  17. <dependency>
  18. <groupId>mysql</groupId>
  19. <artifactId>mysql-connector-java</artifactId>
  20. </dependency>
  21. <!-- lombok -->
  22. <dependency>
  23. <groupId>org.projectlombok</groupId>
  24. <artifactId>lombok</artifactId>
  25. <optional>true</optional>
  26. </dependency>
  27. <!-- mybatis-plus -->
  28. <dependency>
  29. <groupId>com.baomidou</groupId>
  30. <artifactId>mybatis-plus-boot-starter</artifactId>
  31. <version>3.1.1</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>com.baomidou</groupId>
  35. <artifactId>mybatis-plus-generator</artifactId>
  36. <version>3.1.1</version>
  37. </dependency>
  38. <!-- swagger2 -->
  39. <dependency>
  40. <groupId>io.springfox</groupId>
  41. <artifactId>springfox-swagger2</artifactId>
  42. <version>2.9.2</version>
  43. </dependency>
  44. <!-- Velocity模板引擎 -->
  45. <dependency>
  46. <groupId>org.apache.velocity</groupId>
  47. <artifactId>velocity-engine-core</artifactId>
  48. <version>2.1</version>
  49. </dependency>
  50. </dependencies>

2、编写代码生成器代码(有说明)

  1. /**
  2. * @Description: 代码生成器
  3. * @author liangshaolian
  4. */
  5. public class CodeGenerator {
  6. /**
  7. * <p>
  8. * 读取控制台内容
  9. * </p>
  10. */
  11. public static String scanner(String tip) {
  12. Scanner scanner = new Scanner(System.in);
  13. StringBuilder help = new StringBuilder();
  14. help.append("请输入" + tip + ":");
  15. System.out.println(help.toString());
  16. if (scanner.hasNext()) {
  17. String ipt = scanner.next();
  18. if (StringUtils.isNotEmpty(ipt)) {
  19. return ipt;
  20. }
  21. }
  22. throw new MybatisPlusException("请输入正确的" + tip + "!");
  23. }
  24. public static void main(String[] args) {
  25. Scanner scanner = new Scanner(System.in);
  26. AutoGenerator generator = new AutoGenerator();
  27. // 全局变量配置
  28. GlobalConfig gc = new GlobalConfig();
  29. String projectPath = System.getProperty("user.dir"); //当前项目
  30. gc.setOutputDir(projectPath+"/src/main/java"); // 输出路径
  31. gc.setFileOverride(true); // 默认 false ,是否覆盖已生成文件
  32. gc.setOpen(false); //默认true ,是否打开输出目录
  33. gc.setEnableCache(false); // 默认false,是否开启二级缓存
  34. gc.setAuthor("liangshaolian"); // 作者
  35. gc.setSwagger2(true); //默认false
  36. gc.setBaseResultMap(true); // 默认false
  37. gc.setDateType(DateType.TIME_PACK); // 时间策略 默认TIME_PACK
  38. gc.setBaseColumnList(true); //默认false 和basemodel相似
  39. gc.setEntityName("%s");
  40. gc.setControllerName("%sController");
  41. gc.setServiceName("I%sService");
  42. gc.setServiceImplName("%sServiceImpl");
  43. gc.setMapperName("I%sMapper");
  44. gc.setXmlName("%sMapper");
  45. gc.setIdType(IdType.AUTO); // 指定生成的主键类型
  46. generator.setGlobalConfig(gc);
  47. // 数据源配置
  48. DataSourceConfig dc = new DataSourceConfig();
  49. dc.setDbQuery(new MySqlQuery()); // 数据库信息查询 //默认mysql
  50. dc.setDbType(DbType.MYSQL);// 数据库类型
  51. dc.setTypeConvert(new MySqlTypeConvert()); //类型转换 默认mysql
  52. dc.setUrl("jdbc:mysql://127.0.0.1:3306/数据库名?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&useSSL=false");
  53. dc.setDriverName("com.mysql.cj.jdbc.Driver");
  54. dc.setUsername("root");
  55. dc.setPassword("密码");
  56. generator.setDataSource(dc);
  57. // 包配置
  58. PackageConfig pc = new PackageConfig();
  59. pc.setParent("com.liang.module");//代码生成到哪个包下面
  60. // pc.setModuleName(""); //此处是所属模块名称
  61. // pc.setEntity("entity"); //默认entity,controller,service,service.impl,mapper,mapper.xml
  62. generator.setPackageInfo(pc);
  63. // 自定义配置
  64. InjectionConfig cfg = new InjectionConfig() {
  65. @Override
  66. public void initMap() {
  67. // to do nothing
  68. }
  69. };
  70. /**
  71. * 将xml生成到resource下面
  72. */
  73. String templatePath = "/templates/mapper.xml.vm"; // Velocity模板
  74. // 自定义输出配置
  75. List<FileOutConfig> focList = new ArrayList<>();
  76. // 自定义配置会被优先输出
  77. focList.add(new FileOutConfig(templatePath) {
  78. @Override
  79. public String outputFile(TableInfo tableInfo) {
  80. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  81. return projectPath + "/src/main/resources/mapper/"
  82. // + pc.getModuleName()
  83. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  84. }
  85. });
  86. cfg.setFileOutConfigList(focList);
  87. generator.setCfg(cfg);
  88. // 配置模板
  89. TemplateConfig tc = new TemplateConfig();
  90. // templates/entity.java 模板路径配置,默认在templates目录下,.vm 后缀不用加
  91. tc.setEntity("templates/entity.java");//使用自定义模板生成实体类
  92. tc.setXml("");
  93. generator.setTemplate(tc);
  94. // 数据库表配置
  95. StrategyConfig sc = new StrategyConfig();
  96. sc.setCapitalMode(false); //是否大写命名 默认false
  97. sc.setSkipView(true); //是否跳过试图 默认false
  98. sc.setNaming(NamingStrategy.underline_to_camel);// 表映射 驼峰命名
  99. sc.setColumnNaming(NamingStrategy.underline_to_camel); // 字段映射 驼峰
  100. sc.setEntityLombokModel(true); //是否使用lombak 默认为false
  101. sc.setRestControllerStyle(true); // 默认false
  102. sc.setEntitySerialVersionUID(true); //默认true
  103. sc.setEntityColumnConstant(true); //默认false 将mysql字段名生成静态变量
  104. sc.setInclude(scanner("表名,多个英文逗号分割").split(",")); //表名,用,隔开 需要生产
  105. // sc.setExclude(""); // 不需要生成 二选一
  106. sc.setEntityTableFieldAnnotationEnable(true); // 默认false 注释
  107. sc.setControllerMappingHyphenStyle(false); //默认false
  108. sc.setLogicDeleteFieldName("status"); // 逻辑删除字段名称
  109. generator.setStrategy(sc);
  110. // 模板引擎
  111. generator.setTemplateEngine(new VelocityTemplateEngine());
  112. generator.execute();
  113. }
  114. }

3、在resources目录下创建templates目录

4、在templates目录下创建entity.java.vm模板(代码如下)

  1. package ${package.Entity};
  2. #foreach($pkg in ${table.importPackages})
  3. import ${pkg};
  4. #end
  5. import io.swagger.annotations.ApiModel;
  6. import io.swagger.annotations.ApiModelProperty;
  7. #if(${entityLombokModel})
  8. import lombok.Data;
  9. import lombok.EqualsAndHashCode;
  10. ##import lombok.experimental.Accessors;
  11. #end
  12. /**
  13. * @Description:$!{table.comment}
  14. * @author ${author}
  15. * @since ${date}
  16. */
  17. @ApiModel(value ="$!{table.comment}")
  18. #if(${entityLombokModel})
  19. @Data
  20. #if(${superEntityClass})
  21. @EqualsAndHashCode(callSuper = true)
  22. #else
  23. @EqualsAndHashCode(callSuper = false)
  24. #end
  25. ##@Accessors(chain = true)
  26. #end
  27. #if(${table.convert})
  28. @TableName("${table.name}")
  29. #end
  30. #if(${superEntityClass})
  31. public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
  32. #elseif(${activeRecord})
  33. public class ${entity} extends Model<${entity}> {
  34. #else
  35. public class ${entity} implements Serializable {
  36. #end
  37. private static final long serialVersionUID = 1L;
  38. ## ---------- BEGIN 字段循环遍历 ----------
  39. #foreach($field in ${table.fields})
  40. #if(${field.keyFlag})
  41. #set($keyPropertyName=${field.propertyName})
  42. #end
  43. #if("$!field.comment" != "")
  44. @ApiModelProperty(value = "${field.comment}")
  45. #end
  46. #if(${field.keyFlag})
  47. ## 主键s
  48. #if(${field.keyIdentityFlag})
  49. @TableId(value = "${field.name}", type = IdType.AUTO)
  50. #elseif(!$null.isNull(${idType}) && "$!idType" != "")
  51. @TableId(value = "${field.name}", type = IdType.${idType})
  52. #elseif(${field.convert})
  53. @TableId("${field.name}")
  54. #end
  55. ## 普通字段
  56. #elseif(${field.fill})
  57. ## ----- 存在字段填充设置 -----
  58. #if(${field.convert})
  59. @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
  60. #else
  61. @TableField(fill = FieldFill.${field.fill})
  62. #end
  63. #elseif(${field.convert})
  64. @TableField("${field.name}")
  65. #end
  66. ## 乐观锁注解
  67. #if(${versionFieldName}==${field.name})
  68. @Version
  69. #end
  70. ## 逻辑删除注解
  71. #if(${logicDeleteFieldName}==${field.name})
  72. @TableLogic
  73. #end
  74. private ${field.propertyType} ${field.propertyName};
  75. #end
  76. ## ---------- END 字段循环遍历 ----------
  77. #if(!${entityLombokModel})
  78. #foreach($field in ${table.fields})
  79. #if(${field.propertyType.equals("boolean")})
  80. #set($getprefix="is")
  81. #else
  82. #set($getprefix="get")
  83. #end
  84. public ${field.propertyType} ${getprefix}${field.capitalName}() {
  85. return ${field.propertyName};
  86. }
  87. #if(${entityBuilderModel})
  88. public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
  89. #else
  90. public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
  91. #end
  92. this.${field.propertyName} = ${field.propertyName};
  93. #if(${entityBuilderModel})
  94. return this;
  95. #end
  96. }
  97. #end
  98. #end
  99. #if(${entityColumnConstant})
  100. #foreach($field in ${table.fields})
  101. public static final String ${field.name.toUpperCase()} = "${field.name}";
  102. #end
  103. #end
  104. #if(${activeRecord})
  105. @Override
  106. protected Serializable pkVal() {
  107. #if(${keyPropertyName})
  108. return this.${keyPropertyName};
  109. #else
  110. return null;
  111. #end
  112. }
  113. #end
  114. #if(!${entityLombokModel})
  115. @Override
  116. public String toString() {
  117. return "${entity}{" +
  118. #foreach($field in ${table.fields})
  119. #if($!{velocityCount}==1)
  120. "${field.propertyName}=" + ${field.propertyName} +
  121. #else
  122. ", ${field.propertyName}=" + ${field.propertyName} +
  123. #end
  124. #end
  125. "}";
  126. }
  127. #end
  128. }

5、基本完成只要运行代码生成器代码,输入表名即可

生成的实体类效果如下:

  1. /**
  2. * @Description:汽车品牌表
  3. */
  4. @ApiModel(value ="汽车品牌表")
  5. @Data
  6. @EqualsAndHashCode(callSuper = false)
  7. @TableName("tn_pur_brand")
  8. public class TnPurBrand implements Serializable {
  9. private static final long serialVersionUID = 1L;
  10. @ApiModelProperty(value = "主键")
  11. @TableId(value = "id", type = IdType.AUTO)
  12. private Long id;
  13. @ApiModelProperty(value = "首字母")
  14. @TableField("initials")
  15. private String initials;
  16. @ApiModelProperty(value = "汽车品牌")
  17. @TableField("brand_name")
  18. private String brandName;
  19. @ApiModelProperty(value = "品牌LOGO")
  20. @TableField("logo")
  21. private String logo;
  22. public static final String ID = "id";
  23. public static final String INITIALS = "initials";
  24. public static final String BRAND_NAME = "brand_name";
  25. public static final String LOGO = "logo";
  26. }