Youzi的知识库 - 递归调用
type: channel
link: https://knowledge.autisn.com/index.php/tag/递归调用/
items: 遍历多级菜单

遍历多级菜单
type: item
date: 2022-03-23T14:59:00+08:00
description: 1.entity增加字段/** * 所有的子分类 * @TableField(exist = false)表示这个在表的字段里面不存在 */ @TableField(exist = false) private List<CategoryEntity> children;2.service写方法/** * 遍历菜单树结构 * @return */ List<CategoryEntity> listWithTree();3.serviceimpl写业务@Override public List<CategoryEntity> listWithTree() { //1.查出所有分类 List<CategoryEntity> entities = baseMapper.selectList(null); //2.组装成父子的树型结构 //2.1找到所有的一级分类 List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0 ) .map((menu)->{menu.setChildren(getChildrens(menu,entities)); return menu;}) .sorted((menu1,menu2)->{return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());}) .collect(Collectors.toList()); return level1Menus; } /** * 递归查找所有菜单的子菜单 * 获取某一个菜单的子菜单 * @param root 当前菜单 * @param all 所有菜单 * @return */ private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){ List<CategoryEntity> children = all.stream().filter(categoryEntity -> { return categoryEntity.getParentCid().equals(root.getCatId()); }).map(categoryEntity -> { //1.找到子菜单 categoryEntity.setChildren(getChildrens(categoryEntity, all)); return categoryEntity; }).sorted((menu1, menu2) -> { //2.菜单的排序 getSort()可能为空，所以需要处理一下，不处理为空指针异常 return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()); }).collect(Collectors.toList()); return children; }4.controller层/** * 查出所有分类以及子分类，以树型结构组装起来 */ @RequestMapping("/list/tree") public R list(){ List<CategoryEntity> entities = categoryService.listWithTree(); return R.ok().put("data", entities); }5.表结构/* Navicat Premium Data Transfer Source Server : youzi Source Server Type : MySQL Source Server Version : 50736 Source Host : 106.13.234.61:3306 Source Schema : gulimall_pms Target Server Type : MySQL Target Server Version : 50736 File Encoding : 65001 Date: 23/03/2022 14:54:14 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for…