部门树实现
核心代码:
public List<DeptTree> queryDeptTreeList(){
//查询部门表全部数据
List<DeptTree> allDept = baseMapper.queryDeptTreeList();
//过滤getParentId() == 0:查出所有一级部门
List<DeptTree> treeList = allDept.stream().filter(dept ->
dept.getParentId() == 0
).map((deptFirst) -> {
//map映射方法改变结果,调用getChildrens()方法,把一级部门deptFirst和所有数据allDept作为参数传递,查询所有下级部门
deptFirst.setChildren(getChildrens(deptFirst, allDept));
return deptFirst;
}).collect(Collectors.toList());
return treeList;
}
/**
* 递归查找所有部门的下级部门
*/
private List<DeptTree> getChildrens(DeptTree deptFirst, List<DeptTree> allDept) {
List<DeptTree> chilrdenList = allDept.stream().filter(dept -> {
//在全部数据中,找到和一级部门deptFirst的valueId相等的parentId
return dept.getParentId().equals(deptFirst.getValueId());
}).map(deptId -> {
//递归查询找到下级部门
deptId.setChildren(getChildrens(deptId, allDept));
return deptId;
}).collect(Collectors.toList());
return chilrdenList;
}
xml文件:
<!-- 根据前端页面传入的dept_id,查出所有父级部门 -->
<select id="queryDeptTreeList" resultMap="deptTree" parameterType="java.util.Map">
select dept_id,parent_id AS "parentId",name,dept_id as "deptId",name as "deptName",concat(dept_id,'dept') as "dept_idName" from sys_dept
where del_flag='0'
</select>
返回结果:
"code": 0,
"msg": null,
"data": [
{
"valueId": "1",
"parentId": "0",
"title": "顶级部门",
"type": "0",
"children": [
{
"valueId": "2",
"parentId": "1",
"title": "办公室",
"type": "0",
"children": []
},
{
"valueId": "3",
"parentId": "1",
"title": "发展部",
"type": "0",
"children": []
},
{
"valueId": "5",
"parentId": "1",
"title": "财务处",
"type": "0",
"children": [
{
"valueId": "8",
"parentId": "5",
"title": "财务一部",
"type": "0",
"children": []
},
{
"valueId": "9",
"parentId": "5",
"title": "财务二部",
"type": "0",
"children": []
}
]
}
]
}
]
}