1、类目查询
软删除 - > status:数据库中标记为废弃
递归查询多级目录
/**
* @description:
* @author: Dixinkk
* @create: 2022-03-27 23:32
*/
@Service
public class CategoryServiceImpl implements ICategoryService {
@Autowired
private 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)) {
categoryVoList.add(category2CategoryVo(category));
}
}
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 (categoryVo.getId().equals(category.getParentId())) {
subCategoryVoList.add(category2CategoryVo(category));
}
subCategoryVoList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());
categoryVo.setSubCategories(subCategoryVoList);
findSubCategory(subCategoryVoList, categories);
}
}
}
private CategoryVo category2CategoryVo(Category category) {
CategoryVo categoryVo = new CategoryVo();
BeanUtils.copyProperties(category,categoryVo);
return categoryVo;
}
}
排序
//默认升序,加 reversed() -> 降序
categoryVoList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());
耗时
http(请求微信api)> 磁盘【MySQL(内网 + 磁盘)】 > 内存
所以,避免在for循环
中用http请求和写SQL
2、测试
断言:判断返回状态是否为0即可
public class CategoryServiceTest extends MallApplicationTests {
@Autowired
private ICategoryService categoryService;
@Test
public void selectAll() {
ResponseVo<List<CategoryVo>> responseVo = categoryService.selectAll();
Assert.assertEquals(SUCCESS.getCode(), responseVo.getStatus());
}
}