在工作中,有时候要校验某些具有层级结构的目录数据,是否选择到最后一级。如果逐条去数据库查询,是可以校验的,但是这样性能,相对来说,比较差。下面我们通过递归的方式,将数据一次性从数据库查出来,之后进行校验。
@Override
public Map<String,ViewBusiCatagoryEntity> busiCataLastLevelInfo() {
log.info(new Date().toString());
List<ViewBusiCatagoryEntity> list = this.baseMapper.selectList(new QueryWrapper<>());
Map<Long, List<ViewBusiCatagoryEntity>> collect = list.stream().collect(Collectors.groupingBy(ViewBusiCatagoryEntity::getParCataId));
Map<String,ViewBusiCatagoryEntity> resultMap = new HashMap<>();
for (ViewBusiCatagoryEntity result: list) {
if(result.getParCataId() == 1L){
getMenuTree(result,collect,resultMap);
}
}
return resultMap;
}
private void getMenuTree(ViewBusiCatagoryEntity result, Map<Long,
List<ViewBusiCatagoryEntity>> collect, Map<String, ViewBusiCatagoryEntity> resultMap) {
if(collect.containsKey(result.getCataId())){
for (ViewBusiCatagoryEntity entity :collect.get(result.getCataId())) {
getMenuTree(entity,collect,resultMap);
}
}else {
resultMap.put(result.getCataNamePath(),result);
}
}