一、业务需求
实现一个类似京东官网的一个树形分类。如下图所示,当然,我们在这里并不是实现这样一个网页效果,只是返回后端业务所实现的三级分类。
二、实现代码
1、数据库设计实现
cat_id:分类id,主键id。
name:分类名称。
parent_cid:父分类id,用于查找某一名称下所属子分类。
cat_level:层级
show_status:是否显示
sort:排序,即决定上诉显示位置。
icon:图标。
product_unit:计量单位。
product_count:商品数量。
2、代码设计实现
a、controller层
/** * 查询所有分类信息并以树状形式返回 */ @GetMapping("/list/tree") public R ListTree() { List listTree = categoryService.listTree(); return R.ok().put("listTree", listTree); }
b、service层
/** * 查询所有分类信息并以树状形式返回 */ @Override public List listTree() { //1、查询所有分类信息 List<CategoryEntity> categoryEntities = baseMapper.selectList(null); //2、利用mybatis实现树状结构的实现 //2.1、首先筛选出父结构体,筛选条件menu.getParentCid()== 0 List<CategoryEntity> listTree = categoryEntities.stream().filter( menu -> menu.getParentCid() == 0 ).map( //2.2、映射赋值,即将此menu(categoryEntitie)的属性Children赋值 (menu) -> { menu.setChildren(getListChildren(menu, categoryEntities)); return menu; } ).sorted( //2.3、排序 (menu1, menu2) -> { return (menu1.getSort() == null? 0: menu1.getSort()) - (menu2.getSort() == null? 0: menu2.getSort()); } ).collect(Collectors.toList()); //2.4、收集起来转化成新数组 return listTree; } /** * 给每一个对象进行检查是否有子数组,如果有则赋值 * @param root * @param listTree * @return */ private List<CategoryEntity> getListChildren(CategoryEntity root, List<CategoryEntity> listTree) { List<CategoryEntity> listChildren = listTree.stream().filter( //判断是否有子数组,如果有,过滤出来 (category) -> { return root.getCatId() == category.getParentCid(); } ).map( //循环判断 (category) -> { category.setChildren(getListChildren(category, listTree)); return category; } ).sorted( //排序 (menu1, menu2) -> { return (menu1.getSort() == null? 0: menu1.getSort()) - (menu2.getSort() == null? 0: menu2.getSort()); } ).collect(Collectors.toList()); return listChildren; }
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
原创不易,请大家多多支持,如有问题或建议,请留言,积极采纳。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------