电商系统:分类模块

一、功能描述

查找多级目录,返回结果如下

img

二、查询目录

1、先查询出一级目录,再递归查询多级目录

2、根据sortorder对目录进行排序

@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public ResponseVO<List<CategoryVO>> selectAll() {
        List<CategoryVO> categoryVOList = new ArrayList<>();
        List<Category> categories = categoryMapper.selectAll();

        for(Category category : categories){
            if(category.getParentId().equals(ROOT_PARENT_ID)){
                CategoryVO categoryVO = new CategoryVO();
                BeanUtils.copyProperties(category, categoryVO);
                categoryVOList.add(categoryVO);
            }
        }
        categoryVOList.sort(Comparator.comparing(CategoryVO::getSortOrder).reversed());
        //查询子目录
        findSubCategory(categoryVOList, categories);

        return ResponseVO.success(categoryVOList);
    }

    private void findSubCategory(List<CategoryVO> categoryVOList, List<Category> categories){
        for(CategoryVO categoryVO : categoryVOList){
            List<CategoryVO> subCategoryVOList = new ArrayList<>();

            for(Category category : categories){
                //如果查到,设置subCategory,继续往下查
                if(category.getParentId().equals(categoryVO.getId())){
                    CategoryVO categoryVO1 = new CategoryVO();
                    BeanUtils.copyProperties(category, categoryVO1);
                    subCategoryVOList.add(categoryVO1);
                }
                subCategoryVOList.sort(Comparator.comparing(CategoryVO::getSortOrder).reversed());
                findSubCategory(subCategoryVOList, categories);
            }
            categoryVO.setSubCategories(subCategoryVOList);
        }
    }
}

发表评论

后才能评论