溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么

發(fā)布時間:2021-11-01 15:40:22 來源:億速云 閱讀:208 作者:iii 欄目:開發(fā)技術

本篇內(nèi)容主要講解“springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么”吧!

因為項目需要,頁面上需要樹形結構的數(shù)據(jù)進行展示(類似下圖這樣),因此需要后端返回相應格式的數(shù)據(jù)。

springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么

我這里用的是springboot+mybatis-plus+mysql,示例的接口是查詢一級權限以及二級權限、三級權限整個權限樹…

下面是導入的maven依賴

 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--數(shù)據(jù)庫連接-->
        <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;
    /**
     * 創(chuàng)建時間
     */

    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注解就表示這個類中的方法都是靜態(tài)方法:

@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創(chuàng)建樹形節(jié)點
     *
     * @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;
	}
}

數(shù)據(jù)查詢接口mapper類

@Mapper
public interface PermissionMapper extends BaseMapper<Permission>{
    
}

數(shù)據(jù)邏輯處理業(yè)務接口

public interface PermissionService extends IService<Permission> {
  

    /**
     * 構建權限樹
     *
     * @param lazy
     * @param parentId
     * @return
     */
    List<PermissionTree> treePermission(boolean lazy, String parentId);
}

數(shù)據(jù)邏輯處理業(yè)務接口實現(xiàn)類

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
/**
     * 構建權限樹:1、不是懶加載情況,查詢?nèi)?
     * 2、是懶加載,根據(jù)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這個參數(shù)失效, 加載所有的權限; true時, 根據(jù)parentId加載
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/getTree", method = RequestMethod.GET)
    public R getTree(boolean lazy, String parentId) {
        return R.ok(permissionService.treePermission(lazy, parentId));
    }
 }

表中測試數(shù)據(jù)如下(注意它的parent_id

springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么

測試一:不是懶加載,查詢整個權限樹。 結果如下。

springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么

{
    "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
        }
    ]
}

測試二:是懶加載,根據(jù)parent_id查詢當前分支。 結果如下。

springboot構造樹形結構數(shù)據(jù)并查詢的方法是什么

{
    "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構造樹形結構數(shù)據(jù)并查詢的方法是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI