数据库中返回所有的一级二级三级菜单,然后通过分类返回给前端
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Long catId;
private String name;
private Long parentCid;
private Integer catLevel;
@TableLogic(value = "1",delval = "0")
private Integer showStatus;
private Integer sort;
private String icon;
private String productUnit;
private Integer productCount;
//添加的属性,非数据库字段
@TableField(exist = false)
private List children;
}
@Override
public List listWithTree() {
//1、查询出所有的分类(select * from pms_category)
List entities = baseMapper.selectList(null);
//2、组装成树形结构
//2.1 查询出所有的一级菜单
List level1 = entities.stream()
.filter(categoryEntity -> categoryEntity.getParentCid().equals(0L))
//映射 改变每个菜单的children信息
.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 level1;
}
private List getChildren(CategoryEntity root, List all){
List children = all.stream()
.filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
.map(categoryEntity -> {
categoryEntity.setChildren(getChildren(categoryEntity,all));
return categoryEntity;
})
.sorted((menu1, menu2) ->
(menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort())
)
//.sorted(Comparator.comparing(CategoryEntity::getSort))
.collect(Collectors.toList());
return children;
}



