把树形结构组装好,具体来说是:给前端返回根节点对象。在根节点中包含子节点,子节点中再包含下一级的子节点。
代码
handler方法中的具体操作
/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/handler/MenuHandler.java
@RequestMapping("/menu/get/whole/tree")
public ResultEntity<Menu> getWholeTree() {
// 1.查询所有的树形节点用于组装
List<Menu> menuList = menuService.getAll();
// 2.将List<Menu>转换为Map<Menu的id,Menu>
Map<Integer,Menu> menuMap = new HashMap<>();
for (Menu menu : menuList) {
Integer id = menu.getId();
menuMap.put(id, menu);
}
// 3.声明变量用于存储根节点对象
Menu rootNode = null;
// 4.遍历List<Menu>
for (Menu menu : menuList) {
// 5.获取当前Menu对象的pid属性
Integer pid = menu.getPid();
// 6.判断pid是否为null
if(pid == null) {
// 7.如果pid为null,说明当前节点是根节点,所以赋值
rootNode = menu;
// 8.根节点没有父节点,所以不必找父节点组装,本次for循环停止执行,继续执行下一次循环
continue ;
}
// 9.既然pid不为null,那么我们根据这个pid查找当前节点的父节点。
Menu father = menuMap.get(pid);
// 10.组装:将menu添加到maybeFather的子节点集合中
father.getChildren().add(menu);
}
return ResultEntity.successWithData(rootNode);
}
备注:尽量不要在代码中出现 嵌套for(N*N), 可以将两个for拆开成先后执行(N+N)
service方法
/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/service/impl/MenuServiceImpl.java
@Service
public class MenuServiceImpl implements MenuService {
@Autowired
private MenuMapper menuMapper;
@Override
public List<Menu> getAll() {
// TODO Auto-generated method stub
return menuMapper.selectByExample(new MenuExample());
}
}
测试
http://localhost:8080/atcrowdfunding-admin-1-webui/menu/get/whole/tree.json