其他分享
首页 > 其他分享> > springboot 实现递归查询菜单

springboot 实现递归查询菜单

作者:互联网

1.模型代码

@TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 菜单名称
     */
    private String name;

    /**
     * 映射父ID
     */
    private Integer parentId;

    @TableField(exist = false)
    private List<MenuInfo> treeList = new ArrayList<>();

2.service代码

/**
     * 获取所有权限
     * @return
     */
    public List<MenuInfo> getMenuList(){
        // 用boot获取分类数据   selectAll在springboot中是获取数据表里的所有数据
        List<MenuInfo> data = menuInfoService.list();
        //定义新的list
        List<MenuInfo> menuList = new ArrayList<>();
        //先找到所有的一级分类
        for(MenuInfo menuInfo : data){
            // 一级菜单的parentId是0
            if(menuInfo.getParentId() == 0){
                menuList.add(menuInfo);
            }
        }
        // 为一级菜单设置子菜单,getChild是递归调用的
        for(MenuInfo parentMenuInfo : menuList){
            parentMenuInfo.setTreeList(getChilde(parentMenuInfo.getId(), data));
        }
        return menuList;
    }

    /**
     * 递归查找子菜单
     *
     * @param id 当前菜单id
     * @param rootList 要查找的列表
     * @return
     */
    private List<MenuInfo> getChilde(Integer id, List<MenuInfo> rootList){
        //子级
        List<MenuInfo> childList = new ArrayList<>();
        for(MenuInfo menuInfo : rootList){
            // 遍历所有节点,将父级id与传过来的id比较
            if(menuInfo.getParentId().equals(id)){
                childList.add(menuInfo);
            }
        }
        // 把子级的子级再循环一遍
        for(MenuInfo sonMenuInfo : childList){
            sonMenuInfo.setTreeList(getChilde(sonMenuInfo.getId(), rootList));
        }
        // 递归退出条件
        if (childList.size() == 0){
            return null;
        }
        return childList;
    }

    @RequestMapping("/tset")
    @ResponseBody
    public List<MenuInfo> test(){
        List<MenuInfo> menuList = this.getMenuList();

        return menuList;

    }

 

标签:菜单,return,springboot,递归,List,id,menuInfo,menuList
来源: https://www.cnblogs.com/wjs2019/p/15933235.html