在controller直接调用即可
这里使用的是mybatis plus
数据库表结构
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
@Override
public List<CategoryEntity> listWithTree() {
// 1.查询出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
// 2.组装成父子树形结构
// 2.1找到所有一级分类
List<CategoryEntity> levelMenus = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map((menu)->{
menu.setChildren(getChildren(menu, entities));
return menu;
}).sorted((menu1, menu2)->{
return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
return levelMenus;
}
/**
* 递归查找所有菜单的子菜单
* @param root
* @param all
* @return
*/
private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity -> {
// 1.找到子菜单
categoryEntity.setChildren(getChildren(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;
}
}