java springboot项目树结构递归查询

记录工作

本文记录树结构递归查询,像菜单栏和部门

首先需要一张表

CREATE TABLE `sys_dict` (
  `id` int NOT NULL AUTO_INCREMENT,
  `parent_id` int NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_bin NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
INSERT INTO sys_dict (parent_id,name) VALUES
	 (0,'中国'),
	 (1,'云南省'),
	 (1,'四川省'),
	 (1,'广西省'),
	 (1,'贵州省'),
	 (1,'广东省'),
	 (2,'昆明市'),
	 (2,'文山市'),
	 (2,'红河州'),
	 (2,'玉溪市');
INSERT INTO sys_dict (parent_id,name) VALUES
	 (3,'成都市'),
	 (3,'广都市'),
	 (3,'绵阳市'),
	 (3,'南充市'),
	 (4,'桂林市'),
	 (5,'贵阳市'),
	 (6,'东莞市'),
	 (7,'五华区'),
	 (8,'砚山县');

接下来就是实体类啦

package com.example.demotest.entity;

import lombok.Data;

import java.util.List;

/**
 * Description :
 * Copyright : Copyright (c) 2022
 * Company : 
 *
 * @author Dshzs月
 * @version 1.0.0
 * @createTime 2022年11月29日 13:55:00
 */
@Data
public class SysDict {

    private String id;

    private String parentId;

    private String orgName;

    /** 子类菜单数据 */
    private List<SysDict> childMenu;
}

后面接controller

    @GetMapping("/menu")
    public List<SysDict> findMenu() {
        return recursionService.findMenu();
    }
@Service
public class RecursionServiceImpl implements RecursionService {

    @Autowired
    private RecursionMapper recursionMapper;
    
    
    @Override
    public List<KeyValueItemVo> tree() {
    List<SysDict> dictList  = recursionMapper.list();
        List<KeyValueItemVo> resultList = new ArrayList<>();
        dictList.forEach(oneLevelDict -> {
            KeyValueItemVo result = new KeyValueItemVo(oneLevelDict.getId(), oneLevelDict.getOrgName());
            // 3、递归整理子级字典
            result.setItems(getChildren(oneLevelDict.getParentId(), dictList));
            resultList.add(result);
        });
        return resultList;
    }
    
    private SysDict getMenuTree(SysDict result, List<SysDict> list) {
        for (SysDict menu : list) {
            //如果父类主键等于传过来实体类的ID
            if (Objects.equals(menu.getParentId(), result.getId())) {
                if (result.getChildMenu() == null) {
                    result.setChildMenu(new ArrayList<>());
                }
                // 递归调用
                result.getChildMenu().add(getMenuTree(menu, list));
            }
        }
        return result;
    }
    
    

到此本文就结束了

posted @ 2022-12-13 17:29  Dshzs月  阅读(656)  评论(0编辑  收藏  举报