GenTableServiceImpl.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package com.ruoyi.gen.service;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.StringWriter;
  6. import java.util.LinkedHashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.function.Function;
  10. import java.util.stream.Collectors;
  11. import java.util.zip.ZipEntry;
  12. import java.util.zip.ZipOutputStream;
  13. import org.apache.commons.io.FileUtils;
  14. import org.apache.commons.io.IOUtils;
  15. import org.apache.velocity.Template;
  16. import org.apache.velocity.VelocityContext;
  17. import org.apache.velocity.app.Velocity;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.stereotype.Service;
  22. import org.springframework.transaction.annotation.Transactional;
  23. import com.alibaba.fastjson.JSON;
  24. import com.alibaba.fastjson.JSONObject;
  25. import com.ruoyi.common.core.constant.Constants;
  26. import com.ruoyi.common.core.constant.GenConstants;
  27. import com.ruoyi.common.core.exception.ServiceException;
  28. import com.ruoyi.common.core.text.CharsetKit;
  29. import com.ruoyi.common.core.utils.StringUtils;
  30. import com.ruoyi.common.security.utils.SecurityUtils;
  31. import com.ruoyi.gen.domain.GenTable;
  32. import com.ruoyi.gen.domain.GenTableColumn;
  33. import com.ruoyi.gen.mapper.GenTableColumnMapper;
  34. import com.ruoyi.gen.mapper.GenTableMapper;
  35. import com.ruoyi.gen.util.GenUtils;
  36. import com.ruoyi.gen.util.VelocityInitializer;
  37. import com.ruoyi.gen.util.VelocityUtils;
  38. /**
  39. * 业务 服务层实现
  40. *
  41. * @author ruoyi
  42. */
  43. @Service
  44. public class GenTableServiceImpl implements IGenTableService
  45. {
  46. private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
  47. @Autowired
  48. private GenTableMapper genTableMapper;
  49. @Autowired
  50. private GenTableColumnMapper genTableColumnMapper;
  51. /**
  52. * 查询业务信息
  53. *
  54. * @param id 业务ID
  55. * @return 业务信息
  56. */
  57. @Override
  58. public GenTable selectGenTableById(Long id)
  59. {
  60. GenTable genTable = genTableMapper.selectGenTableById(id);
  61. setTableFromOptions(genTable);
  62. return genTable;
  63. }
  64. /**
  65. * 查询业务列表
  66. *
  67. * @param genTable 业务信息
  68. * @return 业务集合
  69. */
  70. @Override
  71. public List<GenTable> selectGenTableList(GenTable genTable)
  72. {
  73. return genTableMapper.selectGenTableList(genTable);
  74. }
  75. /**
  76. * 查询据库列表
  77. *
  78. * @param genTable 业务信息
  79. * @return 数据库表集合
  80. */
  81. @Override
  82. public List<GenTable> selectDbTableList(GenTable genTable)
  83. {
  84. return genTableMapper.selectDbTableList(genTable);
  85. }
  86. /**
  87. * 查询据库列表
  88. *
  89. * @param tableNames 表名称组
  90. * @return 数据库表集合
  91. */
  92. @Override
  93. public List<GenTable> selectDbTableListByNames(String[] tableNames)
  94. {
  95. return genTableMapper.selectDbTableListByNames(tableNames);
  96. }
  97. /**
  98. * 查询所有表信息
  99. *
  100. * @return 表信息集合
  101. */
  102. @Override
  103. public List<GenTable> selectGenTableAll()
  104. {
  105. return genTableMapper.selectGenTableAll();
  106. }
  107. /**
  108. * 修改业务
  109. *
  110. * @param genTable 业务信息
  111. * @return 结果
  112. */
  113. @Override
  114. @Transactional
  115. public void updateGenTable(GenTable genTable)
  116. {
  117. String options = JSON.toJSONString(genTable.getParams());
  118. genTable.setOptions(options);
  119. int row = genTableMapper.updateGenTable(genTable);
  120. if (row > 0)
  121. {
  122. for (GenTableColumn cenTableColumn : genTable.getColumns())
  123. {
  124. genTableColumnMapper.updateGenTableColumn(cenTableColumn);
  125. }
  126. }
  127. }
  128. /**
  129. * 删除业务对象
  130. *
  131. * @param tableIds 需要删除的数据ID
  132. * @return 结果
  133. */
  134. @Override
  135. @Transactional
  136. public void deleteGenTableByIds(Long[] tableIds)
  137. {
  138. genTableMapper.deleteGenTableByIds(tableIds);
  139. genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
  140. }
  141. /**
  142. * 导入表结构
  143. *
  144. * @param tableList 导入表列表
  145. */
  146. @Override
  147. @Transactional
  148. public void importGenTable(List<GenTable> tableList)
  149. {
  150. String operName = SecurityUtils.getUsername();
  151. try
  152. {
  153. for (GenTable table : tableList)
  154. {
  155. String tableName = table.getTableName();
  156. GenUtils.initTable(table, operName);
  157. int row = genTableMapper.insertGenTable(table);
  158. if (row > 0)
  159. {
  160. // 保存列信息
  161. List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
  162. for (GenTableColumn column : genTableColumns)
  163. {
  164. GenUtils.initColumnField(column, table);
  165. genTableColumnMapper.insertGenTableColumn(column);
  166. }
  167. }
  168. }
  169. }
  170. catch (Exception e)
  171. {
  172. throw new ServiceException("导入失败:" + e.getMessage());
  173. }
  174. }
  175. /**
  176. * 预览代码
  177. *
  178. * @param tableId 表编号
  179. * @return 预览数据列表
  180. */
  181. @Override
  182. public Map<String, String> previewCode(Long tableId)
  183. {
  184. Map<String, String> dataMap = new LinkedHashMap<>();
  185. // 查询表信息
  186. GenTable table = genTableMapper.selectGenTableById(tableId);
  187. // 设置主子表信息
  188. setSubTable(table);
  189. // 设置主键列信息
  190. setPkColumn(table);
  191. VelocityInitializer.initVelocity();
  192. VelocityContext context = VelocityUtils.prepareContext(table);
  193. // 获取模板列表
  194. List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
  195. for (String template : templates)
  196. {
  197. // 渲染模板
  198. StringWriter sw = new StringWriter();
  199. Template tpl = Velocity.getTemplate(template, Constants.UTF8);
  200. tpl.merge(context, sw);
  201. dataMap.put(template, sw.toString());
  202. }
  203. return dataMap;
  204. }
  205. /**
  206. * 生成代码(下载方式)
  207. *
  208. * @param tableName 表名称
  209. * @return 数据
  210. */
  211. @Override
  212. public byte[] downloadCode(String tableName)
  213. {
  214. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  215. ZipOutputStream zip = new ZipOutputStream(outputStream);
  216. generatorCode(tableName, zip);
  217. IOUtils.closeQuietly(zip);
  218. return outputStream.toByteArray();
  219. }
  220. /**
  221. * 生成代码(自定义路径)
  222. *
  223. * @param tableName 表名称
  224. */
  225. @Override
  226. public void generatorCode(String tableName)
  227. {
  228. // 查询表信息
  229. GenTable table = genTableMapper.selectGenTableByName(tableName);
  230. // 设置主子表信息
  231. setSubTable(table);
  232. // 设置主键列信息
  233. setPkColumn(table);
  234. VelocityInitializer.initVelocity();
  235. VelocityContext context = VelocityUtils.prepareContext(table);
  236. // 获取模板列表
  237. List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
  238. for (String template : templates)
  239. {
  240. if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
  241. {
  242. // 渲染模板
  243. StringWriter sw = new StringWriter();
  244. Template tpl = Velocity.getTemplate(template, Constants.UTF8);
  245. tpl.merge(context, sw);
  246. try
  247. {
  248. String path = getGenPath(table, template);
  249. FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
  250. }
  251. catch (IOException e)
  252. {
  253. throw new ServiceException("渲染模板失败,表名:" + table.getTableName());
  254. }
  255. }
  256. }
  257. }
  258. /**
  259. * 同步数据库
  260. *
  261. * @param tableName 表名称
  262. */
  263. @Override
  264. @Transactional
  265. public void synchDb(String tableName)
  266. {
  267. GenTable table = genTableMapper.selectGenTableByName(tableName);
  268. List<GenTableColumn> tableColumns = table.getColumns();
  269. Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));
  270. List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
  271. if (StringUtils.isEmpty(dbTableColumns))
  272. {
  273. throw new ServiceException("同步数据失败,原表结构不存在");
  274. }
  275. List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
  276. dbTableColumns.forEach(column -> {
  277. GenUtils.initColumnField(column, table);
  278. if (tableColumnMap.containsKey(column.getColumnName()))
  279. {
  280. GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
  281. column.setColumnId(prevColumn.getColumnId());
  282. if (column.isList()) {
  283. // 如果是列表,继续保留字典类型
  284. column.setDictType(prevColumn.getDictType());
  285. }
  286. genTableColumnMapper.updateGenTableColumn(column);
  287. } else {
  288. genTableColumnMapper.insertGenTableColumn(column);
  289. }
  290. });
  291. List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
  292. if (StringUtils.isNotEmpty(delColumns))
  293. {
  294. genTableColumnMapper.deleteGenTableColumns(delColumns);
  295. }
  296. }
  297. /**
  298. * 批量生成代码(下载方式)
  299. *
  300. * @param tableNames 表数组
  301. * @return 数据
  302. */
  303. @Override
  304. public byte[] downloadCode(String[] tableNames)
  305. {
  306. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  307. ZipOutputStream zip = new ZipOutputStream(outputStream);
  308. for (String tableName : tableNames)
  309. {
  310. generatorCode(tableName, zip);
  311. }
  312. IOUtils.closeQuietly(zip);
  313. return outputStream.toByteArray();
  314. }
  315. /**
  316. * 查询表信息并生成代码
  317. */
  318. private void generatorCode(String tableName, ZipOutputStream zip)
  319. {
  320. // 查询表信息
  321. GenTable table = genTableMapper.selectGenTableByName(tableName);
  322. // 设置主子表信息
  323. setSubTable(table);
  324. // 设置主键列信息
  325. setPkColumn(table);
  326. VelocityInitializer.initVelocity();
  327. VelocityContext context = VelocityUtils.prepareContext(table);
  328. // 获取模板列表
  329. List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
  330. for (String template : templates)
  331. {
  332. // 渲染模板
  333. StringWriter sw = new StringWriter();
  334. Template tpl = Velocity.getTemplate(template, Constants.UTF8);
  335. tpl.merge(context, sw);
  336. try
  337. {
  338. // 添加到zip
  339. zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
  340. IOUtils.write(sw.toString(), zip, Constants.UTF8);
  341. IOUtils.closeQuietly(sw);
  342. zip.flush();
  343. zip.closeEntry();
  344. }
  345. catch (IOException e)
  346. {
  347. log.error("渲染模板失败,表名:" + table.getTableName(), e);
  348. }
  349. }
  350. }
  351. /**
  352. * 修改保存参数校验
  353. *
  354. * @param genTable 业务信息
  355. */
  356. @Override
  357. public void validateEdit(GenTable genTable)
  358. {
  359. if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
  360. {
  361. String options = JSON.toJSONString(genTable.getParams());
  362. JSONObject paramsObj = JSONObject.parseObject(options);
  363. if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
  364. {
  365. throw new ServiceException("树编码字段不能为空");
  366. }
  367. else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
  368. {
  369. throw new ServiceException("树父编码字段不能为空");
  370. }
  371. else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
  372. {
  373. throw new ServiceException("树名称字段不能为空");
  374. }
  375. else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
  376. {
  377. if (StringUtils.isEmpty(genTable.getSubTableName()))
  378. {
  379. throw new ServiceException("关联子表的表名不能为空");
  380. }
  381. else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
  382. {
  383. throw new ServiceException("子表关联的外键名不能为空");
  384. }
  385. }
  386. }
  387. }
  388. /**
  389. * 设置主键列信息
  390. *
  391. * @param table 业务表信息
  392. */
  393. public void setPkColumn(GenTable table)
  394. {
  395. for (GenTableColumn column : table.getColumns())
  396. {
  397. if (column.isPk())
  398. {
  399. table.setPkColumn(column);
  400. break;
  401. }
  402. }
  403. if (StringUtils.isNull(table.getPkColumn()))
  404. {
  405. table.setPkColumn(table.getColumns().get(0));
  406. }
  407. if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
  408. {
  409. for (GenTableColumn column : table.getSubTable().getColumns())
  410. {
  411. if (column.isPk())
  412. {
  413. table.getSubTable().setPkColumn(column);
  414. break;
  415. }
  416. }
  417. if (StringUtils.isNull(table.getSubTable().getPkColumn()))
  418. {
  419. table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
  420. }
  421. }
  422. }
  423. /**
  424. * 设置主子表信息
  425. *
  426. * @param table 业务表信息
  427. */
  428. public void setSubTable(GenTable table)
  429. {
  430. String subTableName = table.getSubTableName();
  431. if (StringUtils.isNotEmpty(subTableName))
  432. {
  433. table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
  434. }
  435. }
  436. /**
  437. * 设置代码生成其他选项值
  438. *
  439. * @param genTable 设置后的生成对象
  440. */
  441. public void setTableFromOptions(GenTable genTable)
  442. {
  443. JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
  444. if (StringUtils.isNotNull(paramsObj))
  445. {
  446. String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
  447. String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
  448. String treeName = paramsObj.getString(GenConstants.TREE_NAME);
  449. String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
  450. String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);
  451. genTable.setTreeCode(treeCode);
  452. genTable.setTreeParentCode(treeParentCode);
  453. genTable.setTreeName(treeName);
  454. genTable.setParentMenuId(parentMenuId);
  455. genTable.setParentMenuName(parentMenuName);
  456. }
  457. }
  458. /**
  459. * 获取代码生成地址
  460. *
  461. * @param table 业务表信息
  462. * @param template 模板文件路径
  463. * @return 生成地址
  464. */
  465. public static String getGenPath(GenTable table, String template)
  466. {
  467. String genPath = table.getGenPath();
  468. if (StringUtils.equals(genPath, "/"))
  469. {
  470. return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
  471. }
  472. return genPath + File.separator + VelocityUtils.getFileName(template, table);
  473. }
  474. }