1. 实体类
java
public class Department{
private Long id; //部门的id
private String name; //部门名字
private Long parent_id; //上级部门id
private Department parent; //上级部门
@JsonInclude(JsonInclude.Include.NON_EMPTY)//数据库不存在该字段
private List<Department> children = new ArrayList<>();
}
2. 算法
java
public List<Department> tree() {
//1.查询所有对象
List<Department> all = departmentMapper.loadAll();
//2.建立id-department关系
HashMap<Long,Department> map = new HashMap<>();
all.forEach(dept->{
map.put(dept.getId(),dept);
});
//3.维护对象之间的关系,List里装所有的祖宗结点
List<Department> list = new ArrayList<>();
for(Department department : all){ //如果没有父节点,是祖宗
if (department.getParent_id() == null){
list.add(department);
continue;
}
//如果department不是祖宗 说明有爹
Long parent_id = department.getParent_id(); //儿子department 拿到他爹的id
Department parent = map.get(parent_id); //根据parent_id找到自己的爹
parent.getChildren().add(department); //department的爹parent 拿出口袋 把儿子装进去
}
return list;
}