java实现递归查询树形结构数据

数据库表(还有一个brforeId)

java实现递归查询树形结构数据_第1张图片

 建一个返回菜单数据的实体类user

package com.example.domain;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.List;

@Data
@TableName("user")
public class User {

    @TableField("user_id")
    private Long userId;

    @TableField("user_name")
    private String userName;

    @TableField("phone")
    private String phone;

    @TableField("user_password")
    private String userPassword;

    @TableField("parent_id")
    private Long parentId;

    @TableField("before_id")
    private Long beforeId;

    @TableField(exist = false)
    private List child;
}

 注:这里省略了get,set方法,childMenu是用于装子类数据的;@TableField(exist = false)表示该属性不为数据库表字段,但是必须使用

业务实现层代码:

package com.example.service;

import com.example.domain.User;

import java.util.List;

public interface UserService {

    /**
     * 获取多级菜单信息
     * @param parentId
     * @return
     */
    List find(Long parentId);

    /**
     *递归查询多级  这是常用的
     * @return
     */
    List find2();

    /**
     * 递归查询多级 并且同级要排序
     * @return
     */
    List find3();

}
package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List find(Long parentId) {
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getParentId, parentId);
        List list = userMapper.selectList(queryWrapper);
        for (User user : list) {
            //递归
            user.setChild(find(user.getUserId()));
        }
        return list;
    }

    @Override
    public List find2() {
        //返回
        List result = new ArrayList<>();
        //查出一级菜单
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getParentId, 0);
        List list = userMapper.selectList(queryWrapper);

        //所有数据
        List allList = userMapper.selectList(null);
        //遍历一级菜单
        for (User user : list) {
            //调用递归==================
            user.setChild(getChildren(user.getUserId(), allList));
            result.add(user);
        }
        return result;
    }

    //当前级id  所有的

    private List getChildren(Long id, List allList) {
        //筛选出满足下一级的
        List list = new ArrayList<>();
        for (User user : allList) {
            if (user.getParentId() == id) {
                list.add(user);
            }
        }
        if (list == null) {
            return null;
        }

        for (User user : list) {
            user.setChild(getChildren(user.getUserId(), allList));
        }
        return list;
    }

    //==================================

    @Override
    public List find3() {
        //返回结果
        List result = new ArrayList<>();
        //查询一级菜单
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getParentId, 0);
        List list = userMapper.selectList(queryWrapper);
        //对一级菜单进行排序
        List list1 = sortMenu(list);
        //所有菜单
        List allList = userMapper.selectList(null);
        //遍历一级菜单
        for (User user : list1) {
            user.setChild(getChildren2(user.getUserId(), allList));
            result.add(user);
        }
        return result;
    }

    private List getChildren2(Long userId, List allList) {
        //查出符合条件的菜单
        List list = new ArrayList<>();
        for (User user : allList) {
            if (user.getParentId() == userId) {
                list.add(user);
            }
        }
        //list.size() == 0 这里很重要 之前没写 直接传过去一个null过去排序 所以会报错
        if (CollectionUtils.isEmpty(list)) {  //list == null || list.size() == 0
            return new ArrayList<>();
        }

        List list1 = sortMenu(list);
        //遍历
        for (User user : list1) {
            user.setChild(getChildren2(user.getUserId(),allList));
        }

        return list1;
    }

    //对同一级的菜单排序
    private List sortMenu(List list) {
        //定义HashMap
        HashMap map = new HashMap<>();
        //遍历list 把所有都加入到hashmap里
        for (User user : list) {
            map.put(user.getBeforeId(),user);
        }
        //找到beforeid为0的 即为第一个
        User user = map.get(0L);  //这个id也是下一个的beforeId
        //返回
        List res = new ArrayList<>();
        res.add(user);
        while (true) {
            Long userId = user.getUserId();
            user = map.get(userId);
            if (user == null) break;
            res.add(user);
        }

        return res;
    }
}

 控制层代码:

package com.example.controller;

import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("menu")
    public List find(@RequestParam Long parentId) {
        return userService.find(parentId);
    }

    @GetMapping
    public List find2() {
        return userService.find2();
    }

    @GetMapping("1")
    public List find3() {
        return userService.find3();
    }
}

测试

java实现递归查询树形结构数据_第2张图片

localhost:8080/users 

localhost:8080/users /1

你可能感兴趣的:(spring,mvc,mybatis,java,1024程序员节)