CodeGenerator.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import cn.hutool.core.util.StrUtil;
  2. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
  3. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  4. import com.baomidou.mybatisplus.generator.AutoGenerator;
  5. import com.baomidou.mybatisplus.generator.InjectionConfig;
  6. import com.baomidou.mybatisplus.generator.config.*;
  7. import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
  8. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  9. import com.baomidou.mybatisplus.generator.config.rules.FileType;
  10. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  11. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  12. import com.mysql.jdbc.Driver;
  13. import java.io.File;
  14. import java.io.FileWriter;
  15. import java.io.IOException;
  16. import java.text.SimpleDateFormat;
  17. import java.util.*;
  18. /**
  19. * 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
  20. */
  21. public class CodeGenerator {
  22. //JDBC配置,请修改为你项目的实际配置
  23. private static final String JDBC_URL = "jdbc:mysql://139.224.213.4:3306/firefly?characterEncoding=utf8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull&useSSL=false";
  24. private static final String JDBC_USERNAME = "firefly";
  25. private static final String JDBC_PASSWORD = "firefly";
  26. private static final String JDBC_DIVER_CLASS_NAME = Driver.class.getName();
  27. private static final String PROJECT_PATH = System.getProperty("user.dir").replaceAll("\\\\","/");//项目在硬盘上的基础路径
  28. private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/template";//模板位置
  29. private static final String JAVA_PATH = "/src/main/java"; //java文件路径
  30. private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径
  31. private static final String AUTHOR = "Generator";//@author
  32. private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date
  33. // MBG相关
  34. public static final String BASE_PACKAGE = "com.winhc.repal";//生成代码所在的基础包名称,可根据自己公司的项目修改(注意:这个配置修改之后需要手工修改src目录项目默认的包路径,使其保持一致,不然会找不到类)
  35. public static final String ENTITY_PACKAGE = BASE_PACKAGE + ".entity";//生成的Model所在包
  36. public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".repository";//生成的Mapper所在包
  37. public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";//生成的Service所在包
  38. public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";//生成的ServiceImpl所在包
  39. public static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";//生成的Controller所在包
  40. public static final String MAPPER_XMP_PATH = RESOURCES_PATH + "/mapper";
  41. public static void main(String[] args) {
  42. genCode("USER_EXT");
  43. }
  44. // 生成文件控制
  45. private static final boolean GEN_CONTROLLER = false;
  46. private static final boolean GEN_ENTITY = true;
  47. private static final boolean GEN_DTO = false;
  48. private static final boolean GEN_VO = false;
  49. private static final boolean GEN_CVT = false;
  50. private static final boolean GEN_SERVICE = false;
  51. private static final boolean GEN_SERVICE_IMPL = false;
  52. private static final boolean GEN_MAPPER = true;
  53. private static final boolean GEN_MAPPER_XML = true;
  54. public static void genCode(String tableName) {
  55. String tableNameCamel = StrUtil.toCamelCase(tableName);
  56. // 代码生成器
  57. AutoGenerator mpg = new AutoGenerator();
  58. // 全局配置
  59. GlobalConfig gc = new GlobalConfig();
  60. gc.setOutputDir(PROJECT_PATH + JAVA_PATH);
  61. gc.setAuthor(AUTHOR);
  62. gc.setOpen(false);
  63. gc.setSwagger2(true); //实体属性 Swagger2 注解
  64. gc.setFileOverride(true); // 是否覆盖已有文件
  65. gc.setServiceName("%sService");
  66. gc.setBaseColumnList(false);
  67. gc.setBaseResultMap(false);
  68. mpg.setGlobalConfig(gc);
  69. // 数据源配置
  70. DataSourceConfig dsc = new DataSourceConfig();
  71. dsc.setUrl(JDBC_URL);
  72. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
  73. dsc.setUsername(JDBC_USERNAME);
  74. dsc.setPassword(JDBC_PASSWORD);
  75. dsc.setTypeConvert(new MySqlTypeConvert());
  76. mpg.setDataSource(dsc);
  77. // 包配置
  78. PackageConfig pc = new PackageConfig();
  79. // pc.setModuleName(scanner("模块名"));
  80. pc.setParent(BASE_PACKAGE);
  81. pc.setEntity("entity");
  82. pc.setMapper("repository");
  83. pc.setXml("");
  84. pc.setService("service");
  85. pc.setServiceImpl("service.impl");
  86. pc.setController("controller");
  87. mpg.setPackageInfo(pc);
  88. // 自定义配置
  89. InjectionConfig cfg = new InjectionConfig() {
  90. @Override
  91. public void initMap() {
  92. Map<String,Object> injectMap = new HashMap<>();
  93. injectMap.put("modelNameUpperCamel",tableNameCamel);
  94. this.setMap(injectMap);
  95. }
  96. };
  97. // 如果模板引擎是 freemarker
  98. //String templatePath = "/templates/mapper.xml.ftl";
  99. // 如果模板引擎是 velocity
  100. // String templatePath = "/templates/mapper.xml.vm";
  101. // 自定义输出配置
  102. List<FileOutConfig> focList = new ArrayList<>();
  103. // 自定义配置会被优先输出
  104. focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
  105. @Override
  106. public String outputFile(TableInfo tableInfo) {
  107. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  108. return PROJECT_PATH + "/src/main/resources/mapper/"
  109. + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  110. }
  111. });
  112. focList.add(new FileOutConfig("/templates/dto.java.ftl") {
  113. @Override
  114. public String outputFile(TableInfo tableInfo) {
  115. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  116. return PROJECT_PATH + JAVA_PATH + packageConvertPath(BASE_PACKAGE + ".model.dto")
  117. + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
  118. }
  119. });
  120. focList.add(new FileOutConfig("/templates/vo.java.ftl") {
  121. @Override
  122. public String outputFile(TableInfo tableInfo) {
  123. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  124. return PROJECT_PATH + JAVA_PATH + packageConvertPath(BASE_PACKAGE + ".model.vo")
  125. + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
  126. }
  127. });
  128. focList.add(new FileOutConfig("/templates/cvt.java.ftl") {
  129. @Override
  130. public String outputFile(TableInfo tableInfo) {
  131. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  132. return PROJECT_PATH + JAVA_PATH + packageConvertPath(BASE_PACKAGE + ".model.cvt")
  133. + tableInfo.getEntityName() + "Convert" + StringPool.DOT_JAVA;
  134. }
  135. });
  136. // mapper文件已存在则不生成
  137. cfg.setFileCreate(new IFileCreate() {
  138. @Override
  139. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
  140. if (!GEN_CONTROLLER && fileType == FileType.CONTROLLER) {
  141. return false;
  142. }
  143. if (!GEN_DTO && filePath.contains("DTO")) {
  144. return false;
  145. }
  146. if (!GEN_VO && filePath.contains("VO")) {
  147. return false;
  148. }
  149. if (!GEN_CVT && filePath.contains("Convert")) {
  150. return false;
  151. }
  152. if (!GEN_ENTITY && fileType == FileType.ENTITY) {
  153. return false;
  154. }
  155. if (!GEN_SERVICE && fileType == FileType.SERVICE) {
  156. return false;
  157. }
  158. if (!GEN_SERVICE_IMPL && fileType == FileType.SERVICE_IMPL) {
  159. return false;
  160. }
  161. if (!GEN_MAPPER && fileType == FileType.MAPPER) {
  162. return false;
  163. }
  164. if (!GEN_MAPPER_XML && fileType == FileType.XML) {
  165. return false;
  166. }
  167. if (!GEN_MAPPER_XML && filePath.contains("Mapper.xml")) {
  168. return false;
  169. }
  170. // 判断自定义文件夹是否需要创建
  171. // checkDir("调用默认方法创建的目录,自定义目录用");
  172. if (!filePath.contains("resources")&&filePath.contains("Mapper.xml")) {
  173. // 已经生成 mapper 文件判断存在,不想重新生成返回 false
  174. return false;
  175. } else if (filePath.contains("resources")&&filePath.contains("Mapper.xml")) {
  176. checkDir(filePath);
  177. }
  178. // 允许生成模板文件
  179. return true;
  180. }
  181. });
  182. cfg.setFileOutConfigList(focList);
  183. mpg.setCfg(cfg);
  184. // 配置模板
  185. TemplateConfig templateConfig = new TemplateConfig();
  186. // 配置自定义输出模板
  187. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  188. templateConfig.setEntity("templates/entity.java");
  189. templateConfig.setMapper("templates/mapper.java");
  190. templateConfig.setService("templates/service.java");
  191. templateConfig.setServiceImpl("templates/serviceImpl.java");
  192. templateConfig.setController("templates/controller.java");
  193. templateConfig.setXml(null);
  194. mpg.setTemplate(templateConfig);
  195. // 策略配置
  196. StrategyConfig strategy = new StrategyConfig();
  197. strategy.setNaming(NamingStrategy.underline_to_camel);
  198. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  199. // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
  200. strategy.setEntityLombokModel(true);
  201. strategy.setRestControllerStyle(true);
  202. // 公共父类
  203. // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
  204. // 写于父类中的公共字段
  205. //strategy.setSuperEntityColumns("id");
  206. // strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
  207. strategy.setInclude(tableName);
  208. strategy.setControllerMappingHyphenStyle(false);
  209. strategy.setTablePrefix(pc.getModuleName() + "_");
  210. mpg.setStrategy(strategy);
  211. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  212. mpg.execute();
  213. }
  214. private static String packageConvertPath(String packageName) {
  215. return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
  216. }
  217. }