Aquisição de estrutura de árvore recursiva de classificação de três níveis de produto
controlador
Adicione um novo método à camada de controle GategoryController do módulo do produto
/**
* 返回三级分类tree
*/
@RequestMapping("/list/tree")
public R listTree(){
List<CategoryEntity> tree = categoryService.getTree();
return R.ok().put("data", tree);
}
entidade
Adicionar estrutura de subclasse
@TableField (exist = false) mybatis-plus annotation-not in the table structure
/**
* 子类category
*/
@TableField(exist = false)
private List<CategoryEntity> child;
serviço
GateService adicionado
List<CategoryEntity> getTree();
Classe de implementação
@Override
public List<CategoryEntity> getTree() {
//查询出所有
List<CategoryEntity> all =baseMapper.selectList(null);
//组装成父子结构——改变category的结构
//找到所有的一级分类
List<CategoryEntity> lv1Menu = all.stream().filter(menu->
menu.getParentCid()== 0
).map((menu)->{
//通过递归找到子分类
menu.setChild(getChild(menu,all));
return menu;
}).sorted((menu1,menu2)->{
return menu1.getSort()-menu2.getSort();
}).collect(Collectors.toList());
return lv1Menu;
}
Entre eles, map () encontra todas as subclasses chamando o método recursivo
private List<CategoryEntity> getChild(CategoryEntity root , List<CategoryEntity> all){
List<CategoryEntity> child = all.stream().filter(menu->
menu.getParentCid()==root.getCatId()).map((menu)->{
//通过递归找到子分类
menu.setChild(getChild(menu,all));
return menu;
}).sorted((menu1,menu2)->{
return menu1.getSort()-menu2.getSort();
}).collect(Collectors.toList());
return child;
}
teste
Iniciar visita ao projeto
http: // localhost: 10000 / produto / categoria / lista / árvore
Get json