实现(树状图)菜单递归的方法

1.数据

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for channel
-- ----------------------------
DROP TABLE IF EXISTS `channel`;
CREATE TABLE `channel`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `channel_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '渠道的名称',
  `parent_id` int(11) NULL DEFAULT NULL COMMENT '父类id',
  `salesman_id` int(11) NULL DEFAULT NULL COMMENT '业务员id',
  `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区域',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '渠道表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of channel
-- ----------------------------
INSERT INTO `channel` VALUES (1, '科达', 0, 1, NULL);
INSERT INTO `channel` VALUES (2, '科利达', 1, 1, NULL);
INSERT INTO `channel` VALUES (3, '科达利', 1, 1, NULL);
INSERT INTO `channel` VALUES (4, '利达科', 2, 2, NULL);
INSERT INTO `channel` VALUES (5, '利科达', 2, 2, NULL);
INSERT INTO `channel` VALUES (6, '达利科', 3, 1, NULL);
INSERT INTO `channel` VALUES (7, '达科利', 3, 2, NULL);

SET FOREIGN_KEY_CHECKS = 1;

2.实体类的创建。get和set方法深略

public class Cannel {
    private Integer id;
    private String channelName;
    private Integer parentId;
    private Integer salesmanId;
    private String area;
    
    private List childCannel;
    

3.mapper.xml的编写



    
        
        
        
        
        
    
    
    
    
    

4.impl方法的编写。其他的control和接口类就不写了

    @Override
    public List findAll(Integer uid) {
        //权限校验
        Integer stationUid = ValidUtils.AdminStation(uid);
        List CannelList = new ArrayList();
        //station返回2,说明有权限,0没有权限 
        if(stationUid==2) {
            List findAll = mapper.findAll();
            for (Cannel cannel : findAll) {
                //判断是否是根节点。为0是跟节点
                if(cannel.getParentId()==0) {
                    CannelList.add(cannel);
                }
            }
            //遍历找到二级节点
            for (Cannel cannel : CannelList) {
                List child = getChild(cannel.getId(),findAll);
                cannel.setChildCannel(child);
            }
        }
        return CannelList;
    }

    private List getChild(Integer id, List findAll) {
        //子菜单列表
        List childList = new ArrayList<>();
        for (Cannel cannel : findAll) {
            if(id.equals(cannel.getParentId())) {
                childList.add(cannel);
            }
        }
        //遍历 获取子菜单的子菜单
        for (Cannel cannel : childList) {
            List child = getChild(cannel.getId(),findAll);
            cannel.setChildCannel(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

你可能感兴趣的:(实现(树状图)菜单递归的方法)