SpringBoot+MyBatisPlus+MySQL8 实现树形结构查询的方法

2025-01-14 23:10:13   小编

在企业级应用开发中,树形结构数据的查询与展示是常见的需求。本文将详细介绍如何使用SpringBoot+MyBatisPlus+MySQL8实现树形结构查询。

搭建SpringBoot项目。通过Spring Initializr快速创建项目,并在pom.xml文件中添加SpringBoot、MyBatisPlus、MySQL驱动等相关依赖。配置好application.yml文件,连接MySQL8数据库。

接着,创建数据库表。假设我们有一个菜单表sys_menu,表结构包含菜单ID、菜单名称、父菜单ID等字段。例如:

CREATE TABLE sys_menu (
    menu_id BIGINT PRIMARY KEY AUTO_INCREMENT,
    menu_name VARCHAR(50),
    parent_id BIGINT DEFAULT 0
);

在实体类方面,创建Menu实体类,使用MyBatisPlus的注解进行表字段映射。

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

@Data
@TableName("sys_menu")
public class Menu {
    private Long menuId;
    private String menuName;
    private Long parentId;
}

Mapper接口使用MyBatisPlus的BaseMapper接口,继承后即可获得基本的数据库操作方法。

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface MenuMapper extends BaseMapper<Menu> {
}

核心的树形结构查询逻辑,我们可以在Service层实现。先查询出所有菜单数据,然后通过递归方法构建树形结构。

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

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

@Service
public class MenuService {
    @Resource
    private MenuMapper menuMapper;

    public List<Menu> buildTree() {
        List<Menu> allMenus = menuMapper.selectList(new QueryWrapper<>());
        List<Menu> rootMenus = new ArrayList<>();
        for (Menu menu : allMenus) {
            if (menu.getParentId() == 0) {
                rootMenus.add(menu);
            }
        }
        for (Menu rootMenu : rootMenus) {
            buildChildTree(rootMenu, allMenus);
        }
        return rootMenus;
    }

    private void buildChildTree(Menu parentMenu, List<Menu> allMenus) {
        List<Menu> childMenus = new ArrayList<>();
        for (Menu menu : allMenus) {
            if (menu.getParentId().equals(parentMenu.getMenuId())) {
                childMenus.add(menu);
                buildChildTree(menu, allMenus);
            }
        }
        parentMenu.setChildren(childMenus);
    }
}

最后,在Controller层提供接口,将构建好的树形结构数据返回给前端。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class MenuController {
    @Resource
    private MenuService menuService;

    @GetMapping("/menus/tree")
    public List<Menu> getMenuTree() {
        return menuService.buildTree();
    }
}

通过以上步骤,利用SpringBoot+MyBatisPlus+MySQL8就可以高效地实现树形结构查询,为前端展示提供有力支持。

TAGS: SpringBoot MySQL8 MyBatisPlus 树形结构查询

欢迎使用万千站长工具!

Welcome to www.zzTool.com