我这里以部门作为例子,一个部门可以由多个子部门,并且子部门还可以拥有子部门信息。
//封装树形数据
@Override
public List<Map<String, Object>> getThreeInfo() {
List<Map<String, Object>> listMap=new ArrayList<>();
//查询最上级部门信息,selectDeptList方法是通过上级部门id查询部门集合,
//如果为一级部门,则上级部门id为-1
List<Department> list = departmentMapper.selectDeptList(-1);
//循环上级部门集合
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
List<Department> list1 = new ArrayList<>();
//封装树形控件需要的数据
Department dept = list.get(i);
map.put("id", dept.getDeptId());
map.put("label", dept.getDeptName());
//给每一个一级部门添加一个为空的children数组。
map.put("children", list1);
//添加子节点
getNodes(map, dept.getDeptId());
listMap.add(map);
}
return listMap;
}
//递归封装子节点的数据
private void getNodes(Map<String, Object> map, Integer superDeptId) {
List<Department> childs = departmentMapper.selectDeptList(superDeptId);
List<Map<String, Object>> childLists = new ArrayList<Map<String, Object>>();
//设置子节点
if (childs != null && childs.size() > 0) {
for (int j = 0; j < childs.size(); j++) {
Map<String, Object> childMap = new HashMap<String, Object>();
Department dept = childs.get(j);
childMap.put("id", dept.getDeptId());
childMap.put("label", dept.getDeptName());
//递归查询子节点,以部门id作为上级部门id 继续递归查询
getNodes(childMap, dept.getDeptId());
childLists.add(childMap);
}
//将子部门数据放到对应一级部门的children中
map.put("children", childLists);
}
}