首先说一下商品分类(表名:product_categoy)数据库的结构,主要就是
category_id:分类id
parent_id:父类的ID(指的是同表中父类的id)
这两个字段,其他的字段名在这里讲没什么太大的意义。
这个是一次性从数据库中将所有数据全部取出减少数据库连接次数,在得到结果的基础上进行递归,递归的大体的思路就是 以根据id查询以它为父类id的所有数据,再得到一个不是以他为父类的数据集合这个集合作为后续递归的基础、随着递归集合也会越来越小。当集合没有数据则终止退出,并返回递归所查出的数据。
serviceImpl的代码:
@Override
public List<TreeVO> findCategoryAndChild(Integer parentId) {
//1.得到所有的分类数据
List<ProductCategoryModel> productCategoryModelList = productCategoryMapper.findAll(parentId);
//2.将数据进行递归 当datas为null的时候则表示没有下级 则推出
return findChild(productCategoryModelList,parentId);
}
/**
*TreeVO 只是用来封装数据的模型类 不用太在意这个
*/
public List<TreeVO> findChild(List<ProductCategoryModel> byParentIds,Integer parentId) {
ArrayList<TreeVO> treeVOS = new ArrayList<>();
//退出条件 没有子类数据则退出
if(byParentIds!=null){
//得到以parentId为父类的集合
List<TreeVO> byParentIdList = byParentIds.stream().filter(e -> e.getParentId().longValue() == parentId.longValue()).collect(Collectors.toList());
//得到不是以parentId为父类的集合
List<TreeVO> byParentIdOtherList = byParentIds.stream().filter(e -> e.getParentId().longValue() != parentId.longValue()).collect(Collectors.toList());
//遍历传递过来这一级别的数据 获取id 根据id查询下一级
for(ProductCategoryModel productCategoryModel:byParentIds){
//进行数据封装 start
TreeVO treeVO = new TreeVO();
treeVO.setId(productCategoryModel.getCategoryId());
treeVO.setLabel(productCategoryModel.getCategoryName());
treeVO.setParentId(productCategoryModel.getParentId());
//判断 如果这条数据的parentId与传递过来的parentId相等则添加进childList中
if(productCategoryModel.getParentId()==parentId){
//并进行 递归操作
treeVO.setChildren(findChild(byParentIdOtherList,productCategoryModel.getCategoryId()));
}
//进行数据封装 end
treeVOS.add(treeVO);
}
return treeVOS;
}
return treeVOS;
}