Service层
@Override
public ResponseResult<List<OneDepartment>> selectDepartment() {
// 获取一级标题的数据
List<OneDepartment> finalResult = new ArrayList<>();
List<SystemDepartment> list = systemDepartmentMapper.selectList(new QueryWrapper<SystemDepartment>().ge("id", 0));
list.forEach(item -> {
if(item.getParentId() == 0) {
OneDepartment dept = new OneDepartment();
BeanUtils.copyProperties(item, dept);
finalResult.add(dept);
}
});
// 发现根部门, 递归查询所有子部门
if (finalResult.size() > 0) {
finalResult.forEach(item->{
this.findChildren(item, list);
});
}
return ResponseResult.ok(finalResult);
}
// 递归查询所有子部门
private void findChildren(OneDepartment department, List<SystemDepartment> list){
// 父元素的id,子元素的parentId
Integer id = department.getId();
List<OneDepartment> result = new ArrayList<>();
list.forEach(item->{
if(item.getParentId().equals(id)) {
OneDepartment dept = new OneDepartment();
BeanUtils.copyProperties(item, dept);
result.add(dept);
department.setChildren(result);
findChildren(dept, list);
}
});
}
实体类
@Data
public class OneDepartment {
private Integer id;
private String deptName;
private String level;
private Integer parentId;
private Integer seq;
private String operator;
private String remarks;
private List<OneDepartment> children;
}