PageRenderTime 63ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java

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