- 树形结构的数据必须要有一个父id,创建一个树形结构的实体类,里面要有List childNode,用来存放子节点
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class RoleTree extends BaseEntity {
private Long id;
private String roleName;
private String roleCode;
private String rolePath;
private Long parentId;
private Boolean isEnabled;
private List<RoleTree> childNode;
public RoleTree(Role role){
this.Id = role.getId();
this.roleName = role.getRoleName();
this.roleCode = role.getRoleCode();
this.rolePath = role.getRolePath();
this.parentId = role.getParentId();;
this.isEnabled = role.getIsEnabled();
this.childNode = new ArrayList<>();
}
}
- 重点,业务逻辑
public List<RoleTree> getRoleTree() {
List<Role> roles = baseMapper.selectList(Wrappers.emptyWrapper());
Map<Long, List<RoleTree>> childMap = new HashMap<>();
List<RoleTree> resultList = new ArrayList<>();
for (Role role : roles) {
RoleTree roleTree = new RoleTree(role);
if (role.getParentId() == 0 || role.getParentId() == null){
resultList.add(roleTree);
}else {
if (childMap.containsKey(role.getParentId())){
childMap.get(role.getParentId()).add(roleTree);
}else {
List<RoleTree> list = new ArrayList<>();
list.add(roleTree);
childMap.put(role.getParentId(), list);
}
}
}
for (RoleTree root : resultList) {
getChild(childMap, Arrays.asList(root));
}
return resultList;
}
private static void getChild(Map<Long, List<RoleTree>> childMap, List<RoleTree> rootList){
for (RoleTree roleTree : rootList){
if (childMap.containsKey(roleTree.getId())){
roleTree.getChildNode().addAll(childMap.get(roleTree.getId()));
getChild(childMap, childMap.get(roleTree.getId()));
}
}
}