1、部门表设计
2、实体
@Data
public class DeptTreeDto {
@ApiModelProperty(value = "部门id")
private Integer deptId;
@ApiModelProperty(value = "部门名称")
private String label;
@ApiModelProperty(value = "上级部门")
private Integer parentId;
private List<DeptTreeDto> children;
@ApiModelProperty(value = "部门所属人员")
private List<UserDeptCd> userList;
}
3、dao层
//获取全部部门数据
List<DeptTreeDto> queryDeptInfoNew();
4、service层
/**
* 获取部门树形查询-新
* @return
*/
List<DeptTreeDto> getDeptTreeNew();
5、实现
/**
* 获取部门树形查询-新
*
* @return
*/
@Override
public List<DeptTreeDto> getDeptTreeNew() {
List<DeptTreeDto> allInfo = tAcsLsUserDoorDao.queryDeptInfoNew(); //全部部门数据
//filter是java8的写法,取得所有parentId为0的数据,也就是一级目录
//map也是java8的写法,用于封装数据,取得他的孩子(也就是下级目录)的数据
List<DeptTreeDto> list = allInfo.stream().filter(deptTreeDto ->
deptTreeDto.getParentId() == 0
).map((menu) -> {
menu.setChildren(getChildrenData(menu, allInfo));
menu.setUserList(tAcsLsUserDoorDao.queryUserDeptCdByDept(menu.getDeptId()));//通过部门id查询所属部门用户
return menu;
}).collect(Collectors.toList());
return list;
}
//获取孩子(下级目录)的方法,递归实现
private List<DeptTreeDto> getChildrenData(DeptTreeDto root, List<DeptTreeDto> all) {
List<DeptTreeDto> children = all.stream().filter(deptTreeDto ->
deptTreeDto.getParentId().equals(root.getDeptId())
).map(deptTreeDto -> {
deptTreeDto.setChildren(getChildrenData(deptTreeDto, all));
deptTreeDto.setUserList(tAcsLsUserDoorDao.queryUserDeptCdByDept(deptTreeDto.getDeptId()));//通过部门id查询所属部门用户
return deptTreeDto;
}).collect(Collectors.toList());
return children;
}
6、controller层
AjaxResult是我封装的返回JSON数据的格式,可以替换成你们的
@ApiOperation(value = "查询部门树形-新递归", notes = "查询部门树形-新递归")
@GetMapping(value = "/getDeptTreeNew")
public AjaxResult getDeptTreeNew() {
try {
return AjaxResult.success(accessControlService.getDeptTreeNew());
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error();
}
}
7、展示