级联更新
@Override public void updateCascade(CmdbCascadeUpdateReq cmdbCascadeUpdateReq) { if (CollUtil.isNotEmpty(cmdbCascadeUpdateReq.getCmdbCascadeLevelReqs())) { saveTopLevel(cmdbCascadeUpdateReq); } }
第一层处理
private void saveTopLevel(CmdbCascadeUpdateReq cmdbCascadeUpdateReq) { Integer mappingId = cmdbCascadeUpdateReq.getMappingId(); Integer customColumnId = cmdbCascadeUpdateReq.getCustomColumnId(); cmdbCascadeUpdateReq.getCmdbCascadeLevelReqs().forEach(req -> { CmdbCascade cmdbCascade = CmdbCascade.builder().id(req.getId()).name(req.getName()).level(req.getLevel()).sortOrder(req.getSortOrder()) .mappingId(mappingId).customColumnId(customColumnId).textId(req.getTextId()).build(); if (cmdbCascade.getId() == null) { baseMapper.insert(cmdbCascade); } else { baseMapper.updateById(cmdbCascade); } if (CollUtil.isNotEmpty(req.getChildren())) { saveSubLevel(req.getChildren(), cmdbCascade.getId(), mappingId, customColumnId); } }); }
子层处理进行递归
private void saveSubLevel(List<CmdbCascadeLevel> cmdbCascadeLevelReqs, int parentId, Integer mappingId, Integer customColumnId) { cmdbCascadeLevelReqs.forEach(req -> { CmdbCascade cmdbCascade = CmdbCascade.builder().name(req.getName()).level(req.getLevel()).sortOrder(req.getSortOrder()) .mappingId(mappingId).customColumnId(customColumnId).textId(req.getTextId()).parentId(parentId).build(); if (cmdbCascade.getId() == null) { baseMapper.insert(cmdbCascade); } else { baseMapper.updateById(cmdbCascade); } if (CollUtil.isNotEmpty(req.getChildren())) { saveSubLevel(req.getChildren(), cmdbCascade.getId(), mappingId, customColumnId); } }); }
数据回显同理
@Override public List<CmdbCascadeLevel> get(CmdbCascadeGetReq cmdbCascadeGetReq) { List<CmdbCascadeLevel> cmdbCascadeLevelResp = new ArrayList<>(); List<CmdbCascadeLevel> cmdbCascades = baseMapper.get(cmdbCascadeGetReq); int maxLevel = cmdbCascades.parallelStream().mapToInt(CmdbCascadeLevel::getLevel).max().getAsInt(); //第一层 List<CmdbCascadeLevel> topCmdbCascadeLevels = cmdbCascades.parallelStream().filter(e -> Objects.isNull(e.getParentId())).collect(Collectors.toList()); //子层 n Map<Integer, List<CmdbCascadeLevel>> subCollect = cmdbCascades.parallelStream().filter(e -> !Objects.isNull(e.getParentId())).collect(Collectors.groupingBy(e -> e.getParentId(), LinkedHashMap::new, Collectors.toList())); topCmdbCascadeLevels.forEach(topCmdbCascadeLevel -> { cmdbCascadeLevelResp.add(topCmdbCascadeLevel); setChildren(subCollect, topCmdbCascadeLevel, maxLevel); }); return cmdbCascadeLevelResp; }
private void setChildren(Map<Integer, List<CmdbCascadeLevel>> subCollect, CmdbCascadeLevel cmdbCascadeLevel, int maxLevel) { List<CmdbCascadeLevel> subCmdbCascadeLevels = subCollect.get(cmdbCascadeLevel.getId()); cmdbCascadeLevel.setChildren(subCmdbCascadeLevels); if (--maxLevel > 1) { int finalMaxLevel = maxLevel; subCmdbCascadeLevels.forEach(subCmdbCascadeLevel -> { setChildren(subCollect, subCmdbCascadeLevel, finalMaxLevel); }); } }