mybatis-plus java构造树形菜单

这里以城市为例子,做树状结构

1.原始树结构

City.java

public class City implements Serializable {
    
    

    @ApiModelProperty(value = "城市id")
    private Integer id;

    @ApiModelProperty(value = "城市名称")
    private String name;

    @ApiModelProperty(value = "城市简介")
    private String info;

    @ApiModelProperty(value = "父级id")
    private Integer parentId;
}

2.返回的树的对象封装

CityNode.java

@Data
public class CityNode implements Serializable {
    
    

    @ApiModelProperty(value = "城市id")
    private Integer id;

    @ApiModelProperty(value = "名称")
    private String name;

    @ApiModelProperty(value = "简介")
    private String info;

    @ApiModelProperty(value = "父级id")
    private Integer parentId;

    private List<CityNode> children;
}

2.传入原始对象,构造成树结构

    public Result getTree(String name) {
    
    
        //获取父节点
        QueryWrapper<City> parentWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
    
    //如果有查询条件,就用查询条件
            parentWrapper.like("name", name);
        } else {
    
    //没有查询条件,查询根节点(父id为0的是根节点)
            parentWrapper.eq("parent_id", 0);
        }
        List<City> parents = this.baseMapper.selectList(parentWrapper);
        if (CollectionUtils.isEmpty(parents)) {
    
    
            return new Result();
        }
        //获取全部
        List<City> all = this.baseMapper.selectList(null);
        //拼起来
        List<CityNode> tree = parents.stream().map(x -> toNode(x, all)).collect(Collectors.toList());
        return new Result(tree);
    }

	//构造成树
    private CityNode toNode(City bean, List<City> all) {
    
    
        CityNode node = new CityNode();
        BeanUtils.copyProperties(bean, node);
        node.setChildren(all.stream()
                .filter(x -> x.getParentId().equals(bean.getId()))
                .map(y -> toNode(y, all))
                .collect(Collectors.toList()));
        return node;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43329956/article/details/120827457
今日推荐