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;

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM