TableInitUtil.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package com.poyee.util;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
  5. import com.baomidou.mybatisplus.generator.config.OutputFile;
  6. import com.baomidou.mybatisplus.generator.config.po.TableField;
  7. import com.poyee.base.controller.BaseController;
  8. import com.poyee.base.mapper.IBaseMapper;
  9. import com.poyee.common.db.EnhanceOtherTemplateEngine;
  10. import com.poyee.common.db.TableInitCustomerUtil;
  11. import com.poyee.common.dto.DbConfigModal;
  12. import com.poyee.common.dto.TableColumnConfigModal;
  13. import com.poyee.common.dto.TableConfigModal;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.jetbrains.annotations.NotNull;
  16. import org.yaml.snakeyaml.Yaml;
  17. import java.io.InputStream;
  18. import java.sql.*;
  19. import java.util.*;
  20. /**
  21. * table工具类
  22. */
  23. @Slf4j
  24. public class TableInitUtil {
  25. static final String tmp_path = "/templates/";
  26. static final String project_path = "C:\\mine\\poyee\\poyee-generator\\src\\main\\";
  27. public static void main(String[] args) {
  28. new TableInitUtil().checkTableConfig(null);
  29. }
  30. public static List<DbConfigModal> checkTableConfig(DbConfigModal req) {
  31. List<DbConfigModal> list = new ArrayList<>();
  32. String sourcePath = "spring.datasource.dynamic.datasource";
  33. //获取配置文件中数据源信息
  34. String dataSource = Objects.isNull(req) ? null : req.getDataSource();
  35. Yaml yaml = new Yaml();
  36. InputStream inputStream = TableInitUtil.class.getClassLoader().getResourceAsStream("application-dev.yml");
  37. Map<String, Object> config = yaml.load(inputStream);
  38. try {
  39. config = getSources(config, sourcePath);
  40. }catch (Exception e){
  41. log.error("获取数据源信息失败:{}",e.getMessage());
  42. throw new RuntimeException("获取数据源信息失败");
  43. }
  44. if(StringUtils.isBlank(dataSource)){
  45. //如果为空则获取所有
  46. Optional.ofNullable((Map<String, Object>) config)
  47. .ifPresent(map -> map.forEach((k, v) -> {
  48. if (v instanceof Map) {
  49. Map<String, String> mmap = (Map<String, String>) v;
  50. DbConfigModal req1 = new DbConfigModal();
  51. req1.setDbUrl(mmap.get("url"));
  52. req1.setDbUsername(mmap.get("username"));
  53. req1.setDbPwd(String.valueOf(mmap.get("password")));
  54. req1.setDriverClassName(mmap.get("driver-class-name"));
  55. req1.setDataSource(k);
  56. list.add(req1);
  57. }
  58. }));
  59. }else{
  60. Map<String,String> dataSourceConfig = (Map<String, String>) config.get(dataSource);
  61. log.info("数据源信息:{}",dataSourceConfig);
  62. req.setDbUrl(dataSourceConfig.get("url"));
  63. req.setDbUsername(dataSourceConfig.get("username"));
  64. req.setDbPwd(String.valueOf(dataSourceConfig.get("password")));
  65. req.setDriverClassName(dataSourceConfig.get("driver-class-name"));
  66. list.add(req);
  67. }
  68. return list;
  69. }
  70. static Map<String, Object> getSources(Map<String, Object> config,String sourcePath) throws Exception{
  71. if(StringUtils.isBlank(sourcePath)){
  72. return config;
  73. }
  74. if (sourcePath.indexOf(".") == 0) {
  75. sourcePath = sourcePath.substring(1);
  76. }
  77. String key = sourcePath.split("\\.")[0];
  78. sourcePath = sourcePath.replaceFirst(key, "");
  79. config = (Map<String, Object>) config.get(key);
  80. return getSources(config,sourcePath);
  81. }
  82. public static List<TableConfigModal> checkTableInfos(@NotNull DbConfigModal config) {
  83. Connection conn = null;
  84. List<TableConfigModal> tableConfigs = new ArrayList<>();
  85. try {
  86. Class.forName(config.getDriverClassName()).newInstance();
  87. conn = DriverManager.getConnection(config.getDbUrl(), config.getDbUsername(), config.getDbPwd());
  88. DatabaseMetaData metaData = conn.getMetaData();
  89. ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
  90. while (tables.next()) {
  91. String tableName = tables.getString("TABLE_NAME");
  92. String tableComment = tables.getString("REMARKS");
  93. tableConfigs.add(new TableConfigModal(tableName, tableComment, null));
  94. }
  95. return tableConfigs;
  96. } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
  97. throw new RuntimeException(e);
  98. } finally {
  99. if (conn != null) {
  100. try {
  101. conn.close();
  102. } catch (SQLException e) {
  103. throw new RuntimeException(e);
  104. }
  105. }
  106. }
  107. }
  108. public static List<TableConfigModal> checkTableColumns(@NotNull DbConfigModal config) {
  109. Connection conn = null;
  110. List<TableConfigModal> tableConfigs = new ArrayList<>();
  111. try {
  112. Class.forName(config.getDriverClassName()).newInstance();
  113. conn = DriverManager.getConnection(config.getDbUrl(), config.getDbUsername(), config.getDbPwd());
  114. DatabaseMetaData metaData = conn.getMetaData();
  115. ResultSet tables = metaData.getTables(null, null, config.getTableName(), new String[]{"TABLE"});
  116. while (tables.next()) {
  117. String tableName = tables.getString("TABLE_NAME");
  118. String tableComment = tables.getString("REMARKS");
  119. log.info("表名:{} , 注释:{}", tableName, tableComment);
  120. ResultSet udTs = metaData.getUDTs(null, null, tableName, null);
  121. while (udTs.next()) {
  122. String udTsREMARKS = udTs.getString("REMARKS");
  123. log.info("udTsREMARKS:{} ", udTsREMARKS);
  124. }
  125. List<TableColumnConfigModal> columns = new ArrayList<>();
  126. ResultSet columnsResult = metaData.getColumns(null, null, tableName, null);
  127. while (columnsResult.next()) {
  128. String columnName = columnsResult.getString("COLUMN_NAME");
  129. Integer ordinalPosition = columnsResult.getInt("ORDINAL_POSITION");
  130. String columnDef = columnsResult.getString("COLUMN_DEF");
  131. String isNullable = columnsResult.getString("IS_NULLABLE");
  132. String dataType = columnsResult.getString("DATA_TYPE");
  133. Integer charOctetLength = columnsResult.getInt("CHAR_OCTET_LENGTH");
  134. Integer numericPrecision = columnsResult.getInt("NUM_PREC_RADIX");
  135. Integer numericScale = columnsResult.getInt("DECIMAL_DIGITS");
  136. Integer datetimePrecision = columnsResult.getInt("COLUMN_SIZE");
  137. String columnType = columnsResult.getString("TYPE_NAME");
  138. String columnComment = columnsResult.getString("REMARKS");
  139. TableColumnConfigModal column = new TableColumnConfigModal();
  140. column.setColumnName(columnName);
  141. column.setColumnType(columnType);
  142. column.setColumnComment(columnComment);
  143. column.setColumnDefault(columnDef);
  144. column.setIsNullable(isNullable);
  145. column.setCharacterOctetLength(charOctetLength);
  146. column.setDataType(dataType);
  147. column.setDatetimePrecision(datetimePrecision);
  148. column.setNumericPrecision(numericPrecision);
  149. column.setNumericScale(numericScale);
  150. column.setColumnType(columnType);
  151. column.setOrdinalPosition(ordinalPosition);
  152. columns.add(column);
  153. }
  154. tableConfigs.add(new TableConfigModal(tableName, tableComment, columns));
  155. }
  156. return tableConfigs;
  157. } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
  158. throw new RuntimeException(e);
  159. } finally {
  160. if (conn != null) {
  161. try {
  162. conn.close();
  163. } catch (SQLException e) {
  164. throw new RuntimeException(e);
  165. }
  166. }
  167. }
  168. }
  169. /**
  170. * 生成工具
  171. *
  172. * @param config
  173. */
  174. public static void generation(TableConfigModal config) {
  175. FastAutoGenerator.create(config.getDbUrl(), config.getDbUsername(), config.getDbPwd())
  176. .globalConfig(builder -> {
  177. builder.author(config.getAuthor()) // 设置作者
  178. .fileOverride() // 覆盖已生成文件
  179. .outputDir(config.getJavaProjectPath() + "java"); // 指定输出目录
  180. if (config.isOpenSwagger()) { // 开启 swagger 模式
  181. builder.enableSwagger();
  182. }
  183. })
  184. .packageConfig(builder -> {
  185. Map<OutputFile, String> outputFileStringMap = new HashMap<>();
  186. outputFileStringMap.put(OutputFile.xml, config.getJavaProjectPath() + "resources\\mapper"); // 设置mapperXml生成路径
  187. outputFileStringMap.put(OutputFile.other, config.getVueProjectPath() + "views");// 设置pages生成路径
  188. builder.parent(config.getJavaPackage()) // 设置父包名
  189. .moduleName(config.getJavaModule())//模块名
  190. .other("dto")
  191. .pathInfo(outputFileStringMap)
  192. ;
  193. System.out.println(builder);
  194. })
  195. .injectionConfig(builder -> {
  196. builder.customFile(checkOtherTemplates(config))
  197. .beforeOutputFile((tableInfo, stringObjectMap) -> {
  198. List<TableField> fields = tableInfo.getFields();
  199. fields.forEach(field -> {
  200. String propertyName = field.getPropertyName();
  201. if (StringUtils.isNotBlank(propertyName)) {
  202. if (!Objects.isNull(config.getCustomMap())) {
  203. Map<String, Object> customeMap =
  204. Optional.ofNullable(config.getCustomMap()
  205. .get(propertyName))
  206. .orElse(new HashMap<>());
  207. field.setCustomMap(customeMap);
  208. } else {
  209. field.setCustomMap(TableInitCustomerUtil.checkCustomMap(field));
  210. }
  211. }
  212. });
  213. });
  214. })
  215. .templateConfig(builder -> {
  216. builder.disable()
  217. .entity(config.getTemplates()
  218. .contains("entity") ? tmp_path + "entity.java.vm" : "")
  219. .controller(config.getTemplates()
  220. .contains("controller") ? tmp_path + "controller.java.vm" : "")
  221. .service(config.getTemplates()
  222. .contains("service") ? tmp_path + "service.java.vm" : "")
  223. .serviceImpl(config.getTemplates()
  224. .contains("serviceImpl") ? tmp_path + "serviceImpl.java.vm" : "")
  225. .mapper(config.getTemplates()
  226. .contains("mapper") ? tmp_path + "mapper.java.vm" : "")
  227. .xml(config.getTemplates()
  228. .contains("mapperXml") ? tmp_path + "mapper.xml.vm" : "")
  229. .build();
  230. })
  231. .strategyConfig(builder -> {
  232. builder.addInclude(config.getTableName()) // 设置需要生成的表名
  233. .addTablePrefix("t_", "c_"); // 设置过滤表前缀
  234. if (config.getTemplates()
  235. .contains("entity")) {
  236. builder.entityBuilder()//配置entity
  237. .enableLombok()
  238. .idType(IdType.AUTO)
  239. .enableTableFieldAnnotation()
  240. .fileOverride()
  241. .build();
  242. }
  243. if (config.getTemplates()
  244. .contains("mapper")) {
  245. builder.mapperBuilder()//配置mapper
  246. .superClass(IBaseMapper.class)
  247. .enableBaseResultMap()
  248. .enableBaseColumnList()
  249. .enableMapperAnnotation()
  250. .fileOverride()
  251. .build();
  252. }
  253. if (config.getTemplates()
  254. .contains("service")) {
  255. builder.serviceBuilder()//配置service
  256. .superServiceClass("com.poyee")
  257. .superServiceImplClass("com.poyee")
  258. .fileOverride()
  259. .build();
  260. }
  261. if (config.getTemplates()
  262. .contains("controller")) {
  263. builder.controllerBuilder()
  264. .superClass(BaseController.class)
  265. .enableRestStyle()
  266. .fileOverride()
  267. .build();
  268. }
  269. })
  270. .templateEngine(new EnhanceOtherTemplateEngine())
  271. .execute();
  272. }
  273. /**
  274. * @param config
  275. * @return
  276. */
  277. @NotNull
  278. private static Map<String, String> checkOtherTemplates(TableConfigModal config) {
  279. Map<String, String> map = new HashMap<>();
  280. config.getTemplates()
  281. .forEach(t -> {
  282. switch (t) {
  283. case "Dto":
  284. map.put("Dto.java", tmp_path + "dto.java.vm");
  285. break;
  286. case "index":
  287. map.put("index.vue", tmp_path + "index.vue.vm");
  288. break;
  289. case "index2":
  290. map.put("index.vue", tmp_path + "index2.vue.vm");
  291. break;
  292. case "hold":
  293. map.put("hold.vue", tmp_path + "hold.vue.vm");
  294. break;
  295. }
  296. });
  297. return map;
  298. }
  299. /**
  300. * @param tableName
  301. */
  302. public static void generation(String tableName) {
  303. FastAutoGenerator.create("jdbc:mysql://192.168.207.128:3306/semm", "semm", "123456")
  304. // FastAutoGenerator.create("jdbc:postgresql://localhost:5432/hobby_stocks", "postgres", "123456")
  305. .globalConfig(builder -> {
  306. builder.author("lsz") // 设置作者
  307. .enableSwagger() // 开启 swagger 模式
  308. .fileOverride() // 覆盖已生成文件
  309. .outputDir(project_path + "java"); // 指定输出目录
  310. })
  311. .packageConfig(builder -> {
  312. Map<OutputFile, String> outputFileStringMap = new HashMap<>();
  313. outputFileStringMap.put(OutputFile.xml, project_path + "resources\\mapper"); // 设置mapperXml生成路径
  314. outputFileStringMap.put(OutputFile.other, project_path + "resources\\pages");// 设置pages生成路径
  315. builder.parent("com.poyee") // 设置父包名
  316. .other("dto")
  317. .pathInfo(outputFileStringMap);
  318. })
  319. .injectionConfig(builder -> {
  320. Map<String, String> map = new HashMap<>();
  321. map.put("Dto.java", tmp_path + "dto.java.vm");
  322. map.put("index.vue", tmp_path + "index.vue.vm");
  323. map.put("hold.vue", tmp_path + "hold.vue.vm");
  324. builder.customFile(map)
  325. .beforeOutputFile((tableInfo, stringObjectMap) -> {
  326. List<TableField> fields = tableInfo.getFields();
  327. fields.forEach(field -> field.setCustomMap(TableInitCustomerUtil.checkCustomMap(field)));
  328. });
  329. })
  330. .templateConfig(builder -> {
  331. builder.disable()
  332. .entity(tmp_path + "entity.java.vm")
  333. .controller(tmp_path + "controller.java.vm")
  334. .service(tmp_path + "service.java.vm")
  335. .serviceImpl(tmp_path + "serviceImpl.java.vm")
  336. .mapper(tmp_path + "mapper.java.vm")
  337. .xml(tmp_path + "mapper.xml.vm")
  338. // .entity(path+"dto.java.vm")
  339. .build();
  340. })
  341. .strategyConfig(builder -> { //策略配置
  342. builder.addInclude(tableName) // 设置需要生成的表名
  343. .addTablePrefix("t_", "c_"); // 设置过滤表前缀
  344. builder.entityBuilder()//配置entity
  345. .enableLombok()
  346. .idType(IdType.AUTO)
  347. .enableTableFieldAnnotation()
  348. .fileOverride()
  349. .build();
  350. builder.mapperBuilder()//配置mapper
  351. .enableBaseResultMap()
  352. .enableBaseColumnList()
  353. .enableMapperAnnotation()
  354. .fileOverride()
  355. .build();
  356. builder.serviceBuilder()//配置service
  357. .fileOverride()
  358. .build();
  359. builder.controllerBuilder()
  360. .enableRestStyle()
  361. .fileOverride()
  362. .build();
  363. })
  364. .templateEngine(new EnhanceOtherTemplateEngine())
  365. .execute();
  366. }
  367. }