一個SQL查詢出所有資料--後臺遞迴組tree資料結構
阿新 • • 發佈:2020-11-24
public List<CategoryEntity> listWithTree() { //1、查出所有分類 List<CategoryEntity> entities = baseMapper.selectList(null); //2、找到所有的一級分類 List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid()== 0 ).map((menu)->{
// 這裡可以對資料進行邏輯處理 menu.setChildren(getChildrens(menu,entities)); return menu; }).sorted((menu1,menu2)->{ return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList());return level1Menus; }
//遞迴查詢所有選單的子選單 private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){ List<CategoryEntity> children = all.stream().filter(categoryEntity -> { return categoryEntity.getParentCid() == root.getCatId(); }).map(categoryEntity-> { //1、找到子選單 categoryEntity.setChildren(getChildrens(categoryEntity,all)); return categoryEntity; }).sorted((menu1,menu2)->{ //2、選單的排序 return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList()); return children; }