GenTableServiceImpl.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. // 如果是列表,继续保留字典类型
  285. column.setDictType(prevColumn.getDictType());
  286. }
  287. genTableColumnMapper.updateGenTableColumn(column);
  288. }
  289. else
  290. {
  291. genTableColumnMapper.insertGenTableColumn(column);
  292. }
  293. });
  294. List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
  295. if (StringUtils.isNotEmpty(delColumns))
  296. {
  297. genTableColumnMapper.deleteGenTableColumns(delColumns);
  298. }
  299. }
  300. /**
  301. * 批量生成代码(下载方式)
  302. *
  303. * @param tableNames 表数组
  304. * @return 数据
  305. */
  306. @Override
  307. public byte[] downloadCode(String[] tableNames)
  308. {
  309. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  310. ZipOutputStream zip = new ZipOutputStream(outputStream);
  311. for (String tableName : tableNames)
  312. {
  313. generatorCode(tableName, zip);
  314. }
  315. IOUtils.closeQuietly(zip);
  316. return outputStream.toByteArray();
  317. }
  318. /**
  319. * 查询表信息并生成代码
  320. */
  321. private void generatorCode(String tableName, ZipOutputStream zip)
  322. {
  323. // 查询表信息
  324. GenTable table = genTableMapper.selectGenTableByName(tableName);
  325. // 设置主子表信息
  326. setSubTable(table);
  327. // 设置主键列信息
  328. setPkColumn(table);
  329. VelocityInitializer.initVelocity();
  330. VelocityContext context = VelocityUtils.prepareContext(table);
  331. // 获取模板列表
  332. List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
  333. for (String template : templates)
  334. {
  335. // 渲染模板
  336. StringWriter sw = new StringWriter();
  337. Template tpl = Velocity.getTemplate(template, Constants.UTF8);
  338. tpl.merge(context, sw);
  339. try
  340. {
  341. // 添加到zip
  342. zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
  343. IOUtils.write(sw.toString(), zip, Constants.UTF8);
  344. IOUtils.closeQuietly(sw);
  345. zip.flush();
  346. zip.closeEntry();
  347. }
  348. catch (IOException e)
  349. {
  350. log.error("渲染模板失败,表名:" + table.getTableName(), e);
  351. }
  352. }
  353. }
  354. /**
  355. * 修改保存参数校验
  356. *
  357. * @param genTable 业务信息
  358. */
  359. @Override
  360. public void validateEdit(GenTable genTable)
  361. {
  362. if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
  363. {
  364. String options = JSON.toJSONString(genTable.getParams());
  365. JSONObject paramsObj = JSONObject.parseObject(options);
  366. if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
  367. {
  368. throw new ServiceException("树编码字段不能为空");
  369. }
  370. else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
  371. {
  372. throw new ServiceException("树父编码字段不能为空");
  373. }
  374. else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
  375. {
  376. throw new ServiceException("树名称字段不能为空");
  377. }
  378. else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
  379. {
  380. if (StringUtils.isEmpty(genTable.getSubTableName()))
  381. {
  382. throw new ServiceException("关联子表的表名不能为空");
  383. }
  384. else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
  385. {
  386. throw new ServiceException("子表关联的外键名不能为空");
  387. }
  388. }
  389. }
  390. }
  391. /**
  392. * 设置主键列信息
  393. *
  394. * @param table 业务表信息
  395. */
  396. public void setPkColumn(GenTable table)
  397. {
  398. for (GenTableColumn column : table.getColumns())
  399. {
  400. if (column.isPk())
  401. {
  402. table.setPkColumn(column);
  403. break;
  404. }
  405. }
  406. if (StringUtils.isNull(table.getPkColumn()))
  407. {
  408. table.setPkColumn(table.getColumns().get(0));
  409. }
  410. if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
  411. {
  412. for (GenTableColumn column : table.getSubTable().getColumns())
  413. {
  414. if (column.isPk())
  415. {
  416. table.getSubTable().setPkColumn(column);
  417. break;
  418. }
  419. }
  420. if (StringUtils.isNull(table.getSubTable().getPkColumn()))
  421. {
  422. table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
  423. }
  424. }
  425. }
  426. /**
  427. * 设置主子表信息
  428. *
  429. * @param table 业务表信息
  430. */
  431. public void setSubTable(GenTable table)
  432. {
  433. String subTableName = table.getSubTableName();
  434. if (StringUtils.isNotEmpty(subTableName))
  435. {
  436. table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
  437. }
  438. }
  439. /**
  440. * 设置代码生成其他选项值
  441. *
  442. * @param genTable 设置后的生成对象
  443. */
  444. public void setTableFromOptions(GenTable genTable)
  445. {
  446. JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
  447. if (StringUtils.isNotNull(paramsObj))
  448. {
  449. String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
  450. String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
  451. String treeName = paramsObj.getString(GenConstants.TREE_NAME);
  452. String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
  453. String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);
  454. genTable.setTreeCode(treeCode);
  455. genTable.setTreeParentCode(treeParentCode);
  456. genTable.setTreeName(treeName);
  457. genTable.setParentMenuId(parentMenuId);
  458. genTable.setParentMenuName(parentMenuName);
  459. }
  460. }
  461. /**
  462. * 获取代码生成地址
  463. *
  464. * @param table 业务表信息
  465. * @param template 模板文件路径
  466. * @return 生成地址
  467. */
  468. public static String getGenPath(GenTable table, String template)
  469. {
  470. String genPath = table.getGenPath();
  471. if (StringUtils.equals(genPath, "/"))
  472. {
  473. return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
  474. }
  475. return genPath + File.separator + VelocityUtils.getFileName(template, table);
  476. }
  477. }