1 表结构如下
2.代码如下:controller方法
@GetMapping(value = "/getAllDepartment")
public String getAllDepartment() {
List<Department> departments = departmentDao.selectByParentId(0);
List<DepartmentResp> list = new ArrayList<>();
if (departments.size() > 0) {
departments.stream().forEach(department -> {
DepartmentResp departmentResp = new DepartmentResp();
departmentResp.setId(department.getId());
departmentResp.setParentId(department.getParentId());
departmentResp.setName(department.getName());
List<DepartmentResp> children = getChildren(department.getId());
departmentResp.setFlag(children.size()>0);
departmentResp.setChildrenList(children);
//查询当前人
List<User> users = userDao.selectByDepartmentId(department.getId());
departmentResp.setUserList(users);
list.add(departmentResp);
});
}
String s = JSONObject.toJSONString(list);
return s;
}
public List<DepartmentResp> getChildren(Integer parentId) {
List<DepartmentResp> list = new ArrayList<>();
List<Department> departments = departmentDao.selectByParentId(parentId);
departments.stream().forEach(department -> {
DepartmentResp departmentResp = new DepartmentResp();
departmentResp.setId(department.getId());
departmentResp.setParentId(department.getParentId());
departmentResp.setName(department.getName());
List<DepartmentResp> children = getChildren(department.getId());
departmentResp.setFlag(children.size()>0);
departmentResp.setChildrenList(children);
//查询当前人
List<User> users = userDao.selectByDepartmentId(department.getId());
departmentResp.setUserList(users);
list.add(departmentResp);
});
return list;
}
3. 返回实体类和部门实体类
@Data
@Table(name = "department")
public class Department {
@Id
private Integer id;
private Integer parentId;
private String name;
}
@Data
public class DepartmentResp {
private Integer id;
private Integer parentId;
private String name;
private boolean flag=false;
private List<DepartmentResp> childrenList;
private List<User> userList;
}