左树右表ServiceImpl.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package ${package}.${moduleName}.service.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.util.ArrayUtil;
  4. import cn.hutool.core.lang.tree.Tree;
  5. import cn.hutool.core.lang.tree.TreeNode;
  6. import cn.hutool.core.lang.tree.TreeUtil;
  7. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  8. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  9. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  10. import ${package}.${moduleName}.entity.${ChildClassName}Entity;
  11. import ${package}.${moduleName}.entity.${ClassName}Entity;
  12. import ${package}.${moduleName}.mapper.${ChildClassName}Mapper;
  13. import ${package}.${moduleName}.mapper.${ClassName}Mapper;
  14. import ${package}.${moduleName}.service.${ClassName}Service;
  15. import lombok.RequiredArgsConstructor;
  16. import org.springframework.stereotype.Service;
  17. import org.springframework.transaction.annotation.Transactional;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Objects;
  24. import java.util.Set;
  25. import java.util.function.Function;
  26. /**
  27. * ${tableComment} Service实现类
  28. *
  29. * @author ${author}
  30. * @date ${datetime}
  31. */
  32. #foreach($field in $childFieldList)
  33. #if($field.primaryPk == '1')
  34. #set($childPkField = $field)
  35. #set($childPkGetter = $str.getProperty($childPkField.attrName))
  36. #break
  37. #end
  38. #end
  39. #set($parentGetter = $str.getProperty($parentField))
  40. #set($childFieldGetter = $str.getProperty($childField))
  41. #if($childPkField.attrType == 'Long')
  42. #set($treeRootId = '0L')
  43. #elseif($childPkField.attrType == 'String')
  44. #set($treeRootId = '"0"')
  45. #else
  46. #set($treeRootId = '0')
  47. #end
  48. @Service
  49. @RequiredArgsConstructor
  50. public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper, ${ClassName}Entity> implements ${ClassName}Service {
  51. private final ${ChildClassName}Mapper ${childClassName}Mapper;
  52. /**
  53. * 构建树形结构数据
  54. * @param wrapper 查询条件
  55. * @return 树形结构数据
  56. */
  57. @Override
  58. public List<Tree<${childPkField.attrType}>> buildTree(LambdaQueryWrapper<${ChildClassName}Entity> wrapper) {
  59. List<${ChildClassName}Entity> allList = ${childClassName}Mapper.selectList(wrapper);
  60. if (CollUtil.isEmpty(allList)) {
  61. return new ArrayList<>();
  62. }
  63. List<TreeNode<${childPkField.attrType}>> collect = allList.stream().map(getNodeFunction()).toList();
  64. return TreeUtil.build(collect, ${treeRootId});
  65. }
  66. /**
  67. * 获取树节点详情
  68. * @param ${childClassName} 树节点查询对象
  69. * @return 树节点详情列表
  70. */
  71. @Override
  72. public List<${ChildClassName}Entity> getTreeDetails(${ChildClassName}Entity ${childClassName}) {
  73. return ${childClassName}Mapper.selectList(Wrappers.query(${childClassName}));
  74. }
  75. /**
  76. * 保存树节点
  77. * @param ${childClassName} 树节点对象
  78. * @return 保存结果
  79. */
  80. @Override
  81. @Transactional(rollbackFor = Exception.class)
  82. public Boolean saveTree(${ChildClassName}Entity ${childClassName}) {
  83. ${childClassName}.$str.setProperty($parentField)(validateParentRelation(null, ${childClassName}.$str.getProperty($parentField)()));
  84. return ${childClassName}Mapper.insert(${childClassName}) > 0;
  85. }
  86. /**
  87. * 更新树节点
  88. * @param ${childClassName} 树节点对象
  89. * @return 更新结果
  90. */
  91. @Override
  92. @Transactional(rollbackFor = Exception.class)
  93. public Boolean updateTree(${ChildClassName}Entity ${childClassName}) {
  94. ${childClassName}.$str.setProperty($parentField)(validateParentRelation(${childClassName}.$str.getProperty($childPkField.attrName)(), ${childClassName}.$str.getProperty($parentField)()));
  95. return ${childClassName}Mapper.updateById(${childClassName}) > 0;
  96. }
  97. /**
  98. * 批量删除树节点
  99. * @param ids 树节点ID列表
  100. * @return 删除结果
  101. */
  102. @Override
  103. @Transactional(rollbackFor = Exception.class)
  104. public Boolean removeTreeByIds(${childPkField.attrType}[] ids) {
  105. if (ArrayUtil.isEmpty(ids)) {
  106. return Boolean.TRUE;
  107. }
  108. for (${childPkField.attrType} id : ids) {
  109. if (hasChildNodes(id)) {
  110. throw new RuntimeException("当前节点存在子节点,不能删除");
  111. }
  112. if (hasMainRecords(id)) {
  113. throw new RuntimeException("当前节点已关联主表数据,不能删除");
  114. }
  115. }
  116. return ${childClassName}Mapper.deleteBatchIds(CollUtil.toList(ids)) > 0;
  117. }
  118. /**
  119. * 获取TreeNode转换函数
  120. * @return TreeNode转换函数
  121. */
  122. private Function<${ChildClassName}Entity, TreeNode<${childPkField.attrType}>> getNodeFunction() {
  123. return entity -> {
  124. TreeNode<${childPkField.attrType}> node = new TreeNode<>();
  125. node.setId(entity.$childPkGetter());
  126. node.setName(entity.$str.getProperty($nameField)());
  127. node.setParentId(normalizeParentId(entity.$parentGetter()));
  128. Map<String, Object> extra = new HashMap<>();
  129. #foreach($field in $childFieldList)
  130. extra.put("${field.attrName}", entity.$str.getProperty($field.attrName)());
  131. #end
  132. node.setExtra(extra);
  133. return node;
  134. };
  135. }
  136. /**
  137. * 规范化父节点ID,并校验父子关系
  138. * @param currentId 当前节点ID
  139. * @param parentId 父节点ID
  140. * @return 规范化后的父节点ID
  141. */
  142. private ${childPkField.attrType} validateParentRelation(${childPkField.attrType} currentId, ${childPkField.attrType} parentId) {
  143. ${childPkField.attrType} normalizedParentId = normalizeParentId(parentId);
  144. if (Objects.nonNull(currentId) && Objects.equals(currentId, normalizedParentId)) {
  145. throw new RuntimeException("不能选择当前节点作为父节点");
  146. }
  147. if (Objects.nonNull(currentId) && isDescendant(currentId, normalizedParentId)) {
  148. throw new RuntimeException("不能选择当前节点的后代节点作为父节点");
  149. }
  150. return normalizedParentId;
  151. }
  152. /**
  153. * 判断候选父节点是否是当前节点的后代节点
  154. * @param currentId 当前节点ID
  155. * @param candidateParentId 候选父节点ID
  156. * @return 是否为后代节点
  157. */
  158. private boolean isDescendant(${childPkField.attrType} currentId, ${childPkField.attrType} candidateParentId) {
  159. if (Objects.isNull(currentId) || Objects.isNull(candidateParentId) || Objects.equals(candidateParentId, ${treeRootId})) {
  160. return false;
  161. }
  162. Set<${childPkField.attrType}> visited = new HashSet<>();
  163. ${ChildClassName}Entity parent = ${childClassName}Mapper.selectById(candidateParentId);
  164. while (Objects.nonNull(parent) && visited.add(parent.$childPkGetter())) {
  165. if (Objects.equals(currentId, parent.$childPkGetter())) {
  166. return true;
  167. }
  168. ${childPkField.attrType} nextParentId = parent.$parentGetter();
  169. if (Objects.isNull(nextParentId) || Objects.equals(nextParentId, ${treeRootId})) {
  170. return false;
  171. }
  172. parent = ${childClassName}Mapper.selectById(nextParentId);
  173. }
  174. return false;
  175. }
  176. /**
  177. * 判断是否存在子节点
  178. * @param parentId 父节点ID
  179. * @return 是否存在子节点
  180. */
  181. private boolean hasChildNodes(${childPkField.attrType} parentId) {
  182. LambdaQueryWrapper<${ChildClassName}Entity> wrapper = Wrappers.lambdaQuery();
  183. wrapper.eq(${ChildClassName}Entity::$parentGetter, parentId);
  184. return ${childClassName}Mapper.selectCount(wrapper) > 0;
  185. }
  186. /**
  187. * 判断是否存在关联主表数据
  188. * @param treeId 树节点ID
  189. * @return 是否存在主表数据
  190. */
  191. private boolean hasMainRecords(${childPkField.attrType} treeId) {
  192. LambdaQueryWrapper<${ClassName}Entity> wrapper = Wrappers.lambdaQuery();
  193. wrapper.eq(${ClassName}Entity::$childFieldGetter, treeId);
  194. return baseMapper.selectCount(wrapper) > 0;
  195. }
  196. /**
  197. * 规范化父节点ID
  198. * @param parentId 父节点ID
  199. * @return 规范化后的父节点ID
  200. */
  201. private ${childPkField.attrType} normalizeParentId(${childPkField.attrType} parentId) {
  202. return Objects.nonNull(parentId) ? parentId : ${treeRootId};
  203. }
  204. }