:::info Long 类型的包装类型比较不要直接使用 ==,要用到 longValue() 或者 equals() 因为第 11 和 33 行代码,catId 和 parentCid 是 Long 型的 :::
- 查询出数据库所有分类数据
先获取父ID为0的,也就是最外面一层的大分类,然后在获取的对象类里面加一个 children 属性,将这个大分类下面的所有子分类装进去(children 属性要加注解 @TableField(exist = false))
public List<CategoryEntity> listWithTree() {//1.查出所有分类List<CategoryEntity> entities = baseMapper.selectList(null);//2.组装成父子的树形结构//2.1找到所有一级分类List<CategoryEntity> level1Menus = entities.stream()//过滤出最大一级的父分类.filter(categoryEntity -> categoryEntity.getParentCid().longValue() == 0)//将父分类所有子分类 set 进去.map(e -> {e.setChildren(getChildren(e,entities));return e;})//排序.sorted((menu1,menu2) -> {return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());})//收集成 list 集合.collect(Collectors.toList());return level1Menus;}/**** 递归查找所有菜单的子菜单* @param root 目前的父分类(需要 setChildren 的类)* @param all 所有分类* @return*/private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){List<CategoryEntity> children = all.stream()//过滤该类的子分类.filter((e) -> {return e.getParentCid().longValue() == root.getCatId().longValue();})//将这个分类下的子分类 set 进去.map(e -> {e.setChildren(getChildren(e, all));return e;})//排序//三元运算是为了防止空指针.sorted((menu1,menu2) -> {return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());})//收集成 list 集合.collect(Collectors.toList());return children;}
