多级目录的实现

若想要实现下图的效果:

多级目录的实现_第1张图片

 

 对应的后端代码应该如何写?(递归)

1.mapper

List selectCategoriesByParentId(Integer parentId);

 2.xml

  

 3.service

List listCategoryForCustomer();

4.实现类

@Override
  public List listCategoryForCustomer() {
    ArrayList categoryVOList = new ArrayList<>();
    recursivelyFindCategories(categoryVOList, 0);
    return categoryVOList;
  }

  private void recursivelyFindCategories(List categoryVOList, Integer parentId) {
    //递归获取所有子类别,并组合成为一个“目录树”
    List categoryList = categoryMapper.selectCategoriesByParentId(parentId);
    if (!CollectionUtils.isEmpty(categoryList)) {
      for (int i = 0; i < categoryList.size(); i++) {
        Category category = categoryList.get(i);
        CategoryVO categoryVO = new CategoryVO();
        BeanUtils.copyProperties(category, categoryVO);
        categoryVOList.add(categoryVO);
        recursivelyFindCategories(categoryVO.getChildCategory(), categoryVO.getId());
      }
    }
  }

5.controller

@ApiOperation("前台目录列表")
@GetMapping("category/list")
@ResponseBody
public ApiRestResponse listCategoryForCustomer() {
    List categoryVOS = categoryService.listCategoryForCustomer();
    return ApiRestResponse.success(categoryVOS);
}

你可能感兴趣的:(业务逻辑,java)