第十三章第二节: 产品分类维护 查询功能服务端开发
请求:/product/category/list/tree
响应数据示例:
{
"code": 0,
"msg": "success",
"data": [{
"catId": 1,
"name": "图书、音像、电子书刊",
"parentCid": 0,
"catLevel": 1,
"showStatus": 1,
"sort": 0,
"icon": null,
"productUnit": null,
"productCount": 0,
"children": []
}]
}
操作数据库表:pms_category
1、修改实体类,增加一个属性(子类)
com.applesnt.onlinemall.product.entity.CategoryEntity
/*子分类,注解表示在数据库中不存在这个字段*/
@TableField(exist = false)
private List<CategoryEntity> children;
2、定义查询商品三级分类树的接口
com.applesnt.onlinemall.product.service.CategoryService
/*查询商品三级分类树*/
List<CategoryEntity> listWithTree();
3、定义查询商品三级分类树的接口实现
com.applesnt.onlinemall.product.service.impl.CategoryServiceImpl
/*查询商品三级分类树,调用递归方法getChildrens*/
@Override
public List<CategoryEntity> listWithTree() {
//查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//组装父子结构
List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> {
return 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 -> {
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;
}
4、编写controller控制器类,调用三级分类的接口实现
com.applesnt.onlinemall.product.controller.CategoryController
controller类访问路径说明:
@RequestMapping("product/category")
/**
* 查询出所有分类以及子分类列表,以树形结构组装
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> entities = categoryService.listWithTree();
return R.ok().put("data", entities);
}
5、访问:http://localhost:10000/product/category/list/tree


浙公网安备 33010602011771号