若想要实现下图的效果:
对应的后端代码应该如何写?(递归)
1.mapper
List<Category> selectCategoriesByParentId(Integer parentId);
2.xml
<select id="selectCategoriesByParentId" resultMap="BaseResultMap"
parameterType="int">
select
<include refid="Base_Column_List"/>
from imooc_mall_category
where parent_id=#{parentId}
</select>
3.service
List<CategoryVO> listCategoryForCustomer();
4.实现类
@Override
public List<CategoryVO> listCategoryForCustomer() {
ArrayList<CategoryVO> categoryVOList = new ArrayList<>();
recursivelyFindCategories(categoryVOList, 0);
return categoryVOList;
}
private void recursivelyFindCategories(List<CategoryVO> categoryVOList, Integer parentId) {
//递归获取所有子类别,并组合成为一个“目录树”
List<Category> 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<CategoryVO> categoryVOS = categoryService.listCategoryForCustomer();
return ApiRestResponse.success(categoryVOS);
}