1.创建对应的对象(这里我清除了用不到的数据)
@TableName(value="role")
public class Role
{
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@TableId(type= IdType.AUTO)
private Long id;
/** 名称 */
private String roleName;
/** 父id */
private Long parentId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName= roleName;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("roleName", getRoleName())
.append("parentId", getParentId())
.toString();
}
}
public class RoleVo extends Role {
/**
* 子级节点
**/
private List<RoleVo> children = new ArrayList<>();
public List<RoleVo> getChildren() {
return children;
}
public void setChildren(List<RoleVo> children) {
this.children = children;
}
}
2.这里是对列表数据的查询
这里我用的是mybatisplus,仅仅是用来查询数据列表的
@Override
public List<Role> listRole(Role role) {
LambdaQueryWrapper<Role> lambda = new LambdaQueryWrapper<Role>();
if (StringUtils.isNotEmpty(role.getRoleName())) {
lambda.like(Role::getRoleName, role.getRoleName());
}
return roleMapper.selectList(lambda);
}
3.对查询出的列表转成Tree
@Override
public List<RoleVo> getRoleListTree(Role role) {
//存储所有的权限
Map<Long, RoleVo> roleTree = new HashMap<>();
//查询所有权限列表
List<Role> list = this.listRole(role);
List<RoleVo> arr = new ArrayList<>();
for (Role roleItrm : list) {
RoleVo roleVo = new RoleVo();
BeanUtils.copyProperties(roleItrm, roleVo);
//将所有权限添加到 map 中
roleTree.put(roleItrm.getId(), roleVo);
}
roleTree.entrySet().forEach(item -> {
//获取到当前节点
RoleVo roleVo = item.getValue();
if (roleVo.getParentId() != null && roleVo.getParentId() != 0) {
//根据当前节点查询去map获取父级节点
RoleVo vo = roleTree.get(roleVo.getParentId());
//判断是否有父级节点
if (vo != null){
//给父级节点添加当前子
vo.getChildren().add(roleVo);
}
} else {
// 所有一级节点
arr.add(roleVo);
}
});
for (RoleVo vo: arr) {
// 同步子数据
vo.setChildren(roleTree.get(vo.getId()).getChildren());
}
return arr;
}
4.controller 直接调用方法就可以了
{
"msg": "操作成功",
"code": 200,
"data": [
{
"id": 1,
"roleName": "基础管理",
"parentId": 0,
"children": [
{
"id": 4,
"roleName": "基础信息",
"parentId": 1,
"children": []
}
]
},
{
"id": 2,
"roleName": "用户管理",
"parentId": 0,
"children": [
{
"id": 5,
"roleName": "用户信息",
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"roleName": "菜单管理",
"parentId": 0,
"children": []
}
]
}