多层级菜单数据返回

2019-02-26  本文已影响0人  He_Yifeng

java层多级菜单返回数据问题,菜单的数据存在于数据库的一张数据字典表中,层级为多级,需要以json格式返回给前端,基于jdk8完成。

数据库数据字典存储数据如下(pId=0代表顶级菜单):


类目.png

前端展示如下:


类目.png

因为存在多层级关系,所以我们能想到的便是使用递归的方式将类目的子类目都拿出来,最后转换成json返回。为了避免数据库IO,拿数据我们一次性将改表中的所有数据都拿出。

    public List<DataTypeShow> findAllDataType(DataType dataType){
        //所有类目
        List<DataTypeShow> dts = ......;
        //所有顶级类目
        List<DataTypeShow> tops = dts.stream().filter(x->x.getpId()==0).collect(Collectors.toList());
        //top id作为key,子级作为value组成map
        Map<Integer, List<DataTypeShow>> allMap = dts.stream().collect(Collectors.groupingBy(DataTypeShow::getpId));
        //递归查询
        List<DataTypeShow> list = this.treeDataType(tops, allMap);
        return list;
    }

可以看出首先是获取了所有的类目数据,然后根据pId=0获取顶级菜单的数据,接着根据pId进行分类封装成Map,最后就是调用我们的递归函数。

    public List<DataTypeShow> treeDataType(List<DataTypeShow> top, Map<Integer, List<DataTypeShow>> allMap){
        top.forEach(dataTypeShow -> {
            List<DataTypeShow> temp = allMap.get(dataTypeShow.getId());
            if (temp!=null && !temp.isEmpty()){
                dataTypeShow.setChildren(temp);
                treeDataType(dataTypeShow.getChildren(), allMap);
            }else{
                dataTypeShow.setChildren(new ArrayList<>());
            }
        });
        return top;
    }

这个递归函数很简单,就是循环顶级菜单,看其是否有子类目,如果有就将该类目存入children中,然后再调用函数,如果没有说明该类目就是叶子类目,存入空。

最后封装成相应的json格式,如下:


响应数据格式.png
上一篇 下一篇

猜你喜欢

热点阅读