第一种,递归完成,借助jdk1.8新特性来的stream流来简易开发。
@Override
public List<CategoryEntity> listByTree() {
List<CategoryEntity> allCategory = baseMapper.selectList(null);
List<CategoryEntity> level_1 = allCategory.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map(menu->{
menu.setChildren(selectByChildrens(menu,allCategory));
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
return allCategory;
}
private List<CategoryEntity> selectByChildrens(CategoryEntity root, List<CategoryEntity> allCategory) {
return allCategory.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid().equals(root.getCatId());
}).map(menu->{
menu.setChildren(selectByChildrens(menu,allCategory));
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
}
第二种,通过mybatis plus直接条件查询后通过List<Hash<String,Object>>来映射或者mybatis的xml的sql条件查询可以查出,不过因为有多次对数据库进行查询的操作,io操作是非常耗时的,不推荐。
优化方向即是将数据库内容弄进缓存,不用每次调用就要sql查询即可(之后会添加)