树状结构查询方式:无需连续访问数据库

树状结构查询方式:无需连续访问数据库_第1张图片
2:如上图的结构 查询如下:

public List getCategoryListVO(){
        List mallCategories = mallCategoryMapper.selectList(new QueryWrapper().lambda().eq(MallCategory::getInvalid,0));
        Map> map = new HashMap<>();
        if(mallCategories==null||mallCategories.size()<1){
            return null;
        }
        for (MallCategory mallCategory:mallCategories) {
            if(!map.containsKey(mallCategory.getParentId())){
                List list = new ArrayList<>();
                list.add(mallCategory);
                map.put(mallCategory.getParentId(),list);
            }else{
                map.get(mallCategory.getParentId()).add(mallCategory);
            }
        }
        return createChildMenu(0l, map);
    }

    private List createChildMenu(Long pid, Map> map) {
        if(!map.containsKey(pid)){
            return null;
        }
        List list = map.get(pid);
        Collections.sort(list,(a, b)->(a.getSort() - b.getSort()));
        //输出
        List allCategory = new ArrayList<>();
        for(MallCategory m : list){
            CategoryListVO categoryListVO = new CategoryListVO();
            categoryListVO.setId(m.getId());
            categoryListVO.setName(m.getName());
            categoryListVO.setParentId(m.getParentId());
            allCategory .add(categoryListVO);
            List ll = createChildMenu(m.getId(),map);
            if(!CollectionUtils.isEmpty(ll)) {
                categoryListVO.setChildren(ll);
            }
        }
        return allCategory;
    }

你可能感兴趣的:(mysql)