三级分类查询
1.在哪些类写哪些方法
因为是分类的,所以在com.atguigu.gulimall.product.controller.CategoryController
下写:
/**
* 查出所有分类和子分类,以树形结构组装起来列表
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> entity = categoryService.listWithTree();
return R.ok().put("data", entity);
}
但是listWithTree();这个方法是没有的,alt+inter在com.atguigu.gulimall.product.service.CategoryService生成这个方法:
public interface CategoryService extends IService<CategoryEntity> {
PageUtils queryPage(Map<String, Object> params);
List<CategoryEntity> listWithTree();
}
然后在com.atguigu.gulimall.product.service.impl.CategoryServiceImpl
下实现方法:
2.实现方法的内容
@Override
public List<CategoryEntity> listWithTree() {
//1.查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);//传null,说明没有条件,查询所有
//2.组装成父子的树形结构
//2.1找到所有的一级分类
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)->{
//1.递归找法找到子菜单
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;
}
}
**
注意
**:我们现在查表,查哪个表,就要哪个表的Dao:
com.atguigu.gulimall.product.dao.CategoryDao
原本要在com.atguigu.gulimall.product.service.impl.CategoryServiceImpl下写
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
@Autowired
CategoryDao **categoryDao;**
但是ServiceImpl里面有泛型CategoryDao,点进ServiceImpl里面有
protected M baseMappe
List<CategoryEntity> entities = baseMapper.selectList(null);//传null,说明没有条件,查询所有
//注意,那个服务的baseMapper就是操作哪张表的
查出一级分类,还要查一级分类的子分类,需要在
com.atguigu.gulimall.product.entity.CategoryEntity下添加一个变量:
@TableField(exist = false)//表示不是数据表里的属性
private List<CategoryEntity> children;
接下来的事情就是将子分类都保存在children中