实体类
@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;
@JsonInclude(JsonInclude.Include.NON_EMPTY)/*children没有数据 会返回空数组,加该注解,则不返回该字段*/
@TableField(exist = false)
private List<CategoryEntity> children;
}
controller
/**
* 查出所有分类以及子分类,以树形结构组装
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> list = categoryService.listWithTree();
return R.ok().put("data", list);
}
service->impl
@Override
public List<CategoryEntity> listWithTree() {
//查出所有分类
List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//组装成父子树形结构
List<CategoryEntity> level1Menu = categoryEntities.stream()
.filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map((menu)->{
menu.setChildren(getChildrens(menu,categoryEntities));
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0: menu1.getSort())- (menu2.getSort()==null? 0:menu2.getSort());
}).collect(Collectors.toList());
return level1Menu;
}
private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map((categoryEntity -> {
//找到子菜单
categoryEntity.setChildren(getChildrens(categoryEntity,all));
return categoryEntity;
})).sorted((menu1,menu2)->{
//菜单的排序
return (menu1.getSort()==null?0: menu1.getSort())- (menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
return children;
}