欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot构造树形结构数据并查询的方法

程序员文章站 2022-06-19 13:46:22
因为项目需要,页面上需要树形结构的数据进行展示(类似下图这样),因此需要后端返回相应格式的数据。不说废话,直接开干!!!我这里用的是springboot+mybatis-plus+mysql,示例的接...

因为项目需要,页面上需要树形结构的数据进行展示(类似下图这样),因此需要后端返回相应格式的数据。

springboot构造树形结构数据并查询的方法

不说废话,直接开干!!!

我这里用的是springboot+mybatis-plus+mysql,示例的接口是查询一级权限以及二级权限、三级权限整个权限树…

下面是导入的maven依赖

 		<dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
<!--数据库连接-->
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>druid-spring-boot-starter</artifactid>
            <version>1.1.21</version>
        </dependency>
 
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
        </dependency>
        <!--mybatis增强工具-->
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus-boot-starter</artifactid>
            <version>3.4.0</version>
        </dependency>
  		<dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupid>cn.hutool</groupid>
            <artifactid>hutool-all</artifactid>
            <version>5.0.6</version>
        </dependency>

下面是实体类permission

@data
public class permission implements serializable {
    @tableid
    private string permissionid;
    @notnull(message = "权限名称不能为空")
    private string permissionname;
    /**
     * 权限标识
     */
    @notnull(message = "权限标识不能为空")
    private string permissioncode;
    /**
     * 父菜单id,如果是-1就表示是一级权限菜单。
     */
    @notblank(message = "父菜单id不能为空")
    private string parentid;

    /**
     * 前端url访问接口路径
     */
    private string path;

    /**
     * 排序值
     */
    private integer sort;
    /**
     * 创建时间
     */

    private localdatetime createtime;

    /**
     * 更新时间
     */

    private localdatetime updatetime;

    /**
     * 0--正常 1--删除
     */
    private string delflag;

    public permission() {
        this.permissionid = idutil.simpleuuid();
    }

树形结点类

@data
public class treenode {
    protected string id;
    protected string parentid;
    protected list<treenode> children = new arraylist<treenode>();
    protected boolean haschildren;

   public void addtreenode(treenode node){
       children.add(node);
   }
}

树形结点详细信息类

@data
@equalsandhashcode(callsuper = true)
public class permissiontree extends treenode implements serializable {
    private string permissionname;
    private string permissioncode;
    private string path;
    private integer sort;
    private string label;
    private boolean haschildren;
    public permissiontree() {
    }
}

构建树形结点工具类(关键),在这里我用@utilityclass注解就表示这个类中的方法都是静态方法:

@utilityclass
public class treeutil {


    public <t extends treenode> list<t> build(list<t> treenodes, string root) {
        list<t> trees = new arraylist<>();
        for (t treenode : treenodes) {

            if (root.equals(treenode.getparentid())) {
                trees.add(treenode);
            }

            for (t node : treenodes) {
                if (node.getparentid().equals(treenode.getid())) {
                    treenode.addtreenode(node);
                    treenode.sethaschildren(true);

                }
            }
        }
        return trees;
    }


    /**
     * 通过permission创建树形节点
     *
     * @param permissionlist
     * @param root
     * @return
     */
    public list<permissiontree> buildtree(list<permission> permissionlist, string root) {
        system.out.println(arrays.tostring(permissionlist.toarray()));
        list<permissiontree> treenodelist = new arraylist<>();
        permissiontree treenode = null;
        for (permission permission : permissionlist) {
            treenode = new permissiontree();
            treenode.setid(permission.getpermissionid());
            treenode.setpermissionname(permission.getpermissionname());
            treenode.setpath(permission.getpath());
            treenode.setsort(permission.getsort());
            treenode.setparentid(permission.getparentid());
            treenode.setlabel(permission.getpermissionname());
            treenode.sethaschildren(false);
            treenodelist.add(treenode);
        }
        return treeutil.build(treenodelist, root);
    }
  }

响应消息主体类

/**
 * 响应信息主体
 *
 * @param <t>
 */
@tostring
@noargsconstructor
@allargsconstructor
@accessors(chain = true)
public class r<t> implements serializable {

	private static final long serialversionuid = 1l;

	private int code;

	private string msg;

	private t data;

	public int getcode() {
		return code;
	}

	public void setcode(int code) {
		this.code = code;
	}

	public string getmsg() {
		return msg;
	}

	public void setmsg(string msg) {
		this.msg = msg;
	}

	public t getdata() {
		return data;
	}

	public void setdata(t data) {
		this.data = data;
	}

	public static <t> r<t> ok() {
		return restresult(null, commonconstants.success, commonconstants.msg_success);
	}

	public static <t> r<t> ok(t data) {
		return restresult(data, commonconstants.success, commonconstants.msg_success);
	}

	public static <t> r<t> ok(t data, string msg) {
		return restresult(data, commonconstants.success, msg);
	}

	public static <t> r<t> failed() {
		return restresult(null, commonconstants.fail, null);
	}

	public static <t> r<t> failed(string msg) {
		return restresult(null, commonconstants.fail, msg);
	}

	public static <t> r<t> failed(t data) {
		return restresult(data, commonconstants.fail, null);
	}

	public static <t> r<t> failed(t data, string msg) {
		return restresult(data, commonconstants.fail, msg);
	}

	private static <t> r<t> restresult(t data, int code, string msg) {
		r<t> apiresult = new r<>();
		apiresult.setcode(code);
		apiresult.setdata(data);
		apiresult.setmsg(msg);
		return apiresult;
	}
}

数据查询接口mapper类

@mapper
public interface permissionmapper extends basemapper<permission>{
    
}

数据逻辑处理业务接口

public interface permissionservice extends iservice<permission> {
  

    /**
     * 构建权限树
     *
     * @param lazy
     * @param parentid
     * @return
     */
    list<permissiontree> treepermission(boolean lazy, string parentid);
}

数据逻辑处理业务接口实现类

@service
public class permissionserviceimpl extends serviceimpl<permissionmapper, permission> implements permissionservice {
/**
     * 构建权限树:1、不是懒加载情况,查询全部
     * 2、是懒加载,根据parentid查询
     *
     * @param lazy
     * @param parentid
     * @return
     */

    @override
    public list<permissiontree> treepermission(boolean lazy, string parentid) {

        if (!lazy) {
            return treeutil.buildtree(
                    basemapper.selectlist(wrappers.<permission>lambdaquery().orderbyasc(permission::getsort)),
                    commonconstants.permission_root_id);
        }
        string parent = parentid == null ? commonconstants.permission_root_id : parentid;
        return treeutil.buildtree(
                basemapper.selectlist(wrappers.<permission>lambdaquery().eq(permission::getparentid, parent).orderbyasc(permission::getsort)), parent
        );
    }
}

查询权限树请求接口类

@restcontroller
@requestmapping("/permission")
public class permissioncontroller {
    @autowire
    private permissionservice permissionservice;

    /**
     * 查询权限列表,并以树状结构显示
     *
     * @param lazy 懒加载: false时, parentid这个参数失效, 加载所有的权限; true时, 根据parentid加载
     * @param parentid
     * @return
     */
    @requestmapping(value = "/gettree", method = requestmethod.get)
    public r gettree(boolean lazy, string parentid) {
        return r.ok(permissionservice.treepermission(lazy, parentid));
    }
 }

表中测试数据如下(注意它的parent_id

springboot构造树形结构数据并查询的方法

测试一:不是懒加载,查询整个权限树。 结果如下。

springboot构造树形结构数据并查询的方法

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "id": "1",
            "parentid": "-1",
            "children": [
                {
                    "id": "2",
                    "parentid": "1",
                    "children": [
                        {
                            "id": "3",
                            "parentid": "2",
                            "children": [],
                            "haschildren": false,
                            "permissionname": "update",
                            "permissioncode": null,
                            "path": null,
                            "sort": 3,
                            "label": "update",
                            "owned": false
                        },
                        {
                            "id": "4",
                            "parentid": "2",
                            "children": [],
                            "haschildren": false,
                            "permissionname": "insert_role",
                            "permissioncode": null,
                            "path": null,
                            "sort": 4,
                            "label": "insert_role",
                            "owned": false
                        }
                    ],
                    "haschildren": true,
                    "permissionname": "delete",
                    "permissioncode": null,
                    "path": null,
                    "sort": 2,
                    "label": "delete",
                    "owned": false
                }
            ],
            "haschildren": true,
            "permissionname": "add",
            "permissioncode": null,
            "path": null,
            "sort": 1,
            "label": "add",
            "owned": false
        },
        {
            "id": "5",
            "parentid": "-1",
            "children": [],
            "haschildren": false,
            "permissionname": "role:saverole",
            "permissioncode": null,
            "path": "/role/saverole",
            "sort": 5,
            "label": "role:saverole",
            "owned": false
        }
    ]
}

测试二:是懒加载,根据parent_id查询当前分支。 结果如下。

springboot构造树形结构数据并查询的方法

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "id": "3",
            "parentid": "2",
            "children": [],
            "haschildren": false,
            "permissionname": "update",
            "permissioncode": null,
            "path": null,
            "sort": 3,
            "label": "update",
            "owned": false
        },
        {
            "id": "4",
            "parentid": "2",
            "children": [],
            "haschildren": false,
            "permissionname": "insert_role",
            "permissioncode": null,
            "path": null,
            "sort": 4,
            "label": "insert_role",
            "owned": false
        }
    ]
}

到此这篇关于springboot构造树形结构数据并查询的方法的文章就介绍到这了,更多相关springboot 树形结构并查询内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!