一、前言
在后台代码的开发中,经常碰到有父子关联的表设计,前端要求在后台数据以树形封装进行返回,因此如何建树,或者如何更优雅的建树成了后台开发工作中绕不过去的一个坎,根据工作所需,这里做下总结,以堪后由。
(推荐方式二)
二、方法
1.方式一:独立对象建树
1.1 封装独立对象TreeNode
package cn.keyidea.common.bean;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 树节点实体
*/
@Data
@Schema(name = "TreeNode", description = "树节点实体")
public class TreeNode {
@Schema(description = "节点id", requiredMode = Schema.RequiredMode.REQUIRED)
private Integer id;
@Schema(description = "节点标题", requiredMode = Schema.RequiredMode.REQUIRED)
private String title;
@Schema(description = "子节点", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private List<TreeNode> children;
@Schema(description = "父节点id", requiredMode = Schema.RequiredMode.REQUIRED)
private Integer parentId;
/**
* 节点是否初始为选中状态(如果开启复选框的话),默认 false
*/
@Schema(description = "节点是否初始为选中状态(如果开启复选框的话),默认 false", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean checked;
@Schema(description = "URL地址", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String url;
@Schema(description = "类型", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Integer type;
@Schema(description = "code码", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String code;
@Schema(description = "图标", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String icon;
@Schema(description = "路由地址", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String component;
}
1.2 建树工具类
package cn.keyidea.common.util;
import cn.keyidea.common.bean.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* Tree工具类
*/
public class TreeUtil {
/**
* 两层循环实现建树
*
* @param treeNodes 传入的树节点列表
* @return
*/
public static List<TreeNode> bulidTree(List<TreeNode> treeNodes) {
List<TreeNode> trees = new ArrayList<TreeNode>();
for (TreeNode treeNode : treeNodes) {
if (0 == treeNode.getParentId()) {
trees.add(treeNode);
}
for (TreeNode it : treeNodes) {
if (null != it.getParentId()) {
if (it.getParentId().equals(treeNode.getId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.getChildren().add(it);
}
}
}
}
return trees;
}
}
2.方式二:原生对象建树(推荐)
2.1 以Entity实体作为自身节点
由于菜单一般设计成带有父子项,因此这里以菜单对象做示例。
package cn.keyidea.sys.entity;
import cn.keyidea.common.annotation.EnumValue;
import cn.keyidea.common.bean.BaseModel;
import cn.keyidea.common.valid.GroupAdd;
import cn.keyidea.common.valid.GroupUpdate;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.Comment;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 系统菜单
*
* @author qyd
* @date 2022-10-17
*/
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_menu")
@Schema(name = "SysMenu", description = "系统菜单")
@Entity
@Table(name = "sys_menu")
@Comment("系统菜单表")
public class SysMenu extends BaseModel {
@NotNull(message = "父菜单不能为NULL", groups = {GroupAdd.class, GroupUpdate.class})
@Schema(description = "父菜单ID,一级菜单为0", requiredMode = Schema.RequiredMode.REQUIRED, example = "0")
@Column(name = "parent_id", columnDefinition = "int(10) not null COMMENT '父菜单ID,一级菜单为0'")
private Integer parentId;
// name ==> label
@NotBlank(message = "菜单名称不能为空", groups = {GroupAdd.class, GroupUpdate.class})
@Schema(description = "菜单名称", requiredMode = Schema.RequiredMode.REQUIRED)
@Column(name = "label", columnDefinition = "varchar(100) not null COMMENT '菜单名称'")
private String label;
@NotNull(message = "菜单类型不能为NULL", groups = {GroupAdd.class, GroupUpdate.class})
@EnumValue(intValues = {0, 1, 2, 3}, message = "菜单类型不符合条件")
@Schema(description = "菜单类型:0-系统,1-目录,2-菜单,3-按钮", requiredMode = Schema.RequiredMode.REQUIRED)
@Column(name = "type", columnDefinition = "int(2) not null COMMENT '菜单类型:0-系统,1-目录,2-菜单,3-按钮'")
private Integer type;
@Schema(description = "菜单图标url", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "icon", columnDefinition = "varchar(100) COMMENT '菜单图标url'")
private String icon;
// url ==> key
// 数据库存储url,返回给前端使用key(key为MySQL关键字无法作为存储字段)
@JsonProperty("key")
@Schema(description = "菜单URL", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "url", columnDefinition = "varchar(100) COMMENT '菜单URL'")
private String url;
@Schema(description = "菜单路由地址", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "component", columnDefinition = "varchar(100) COMMENT '菜单路由地址'")
private String component;
@Schema(description = "权限标识,如:user:list", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "perms", columnDefinition = "varchar(100) COMMENT '权限标识,如:user:list'")
private String perms;
@NotNull(message = "排序号不能为NULL", groups = {GroupAdd.class, GroupUpdate.class})
@Schema(description = "排序号", requiredMode = Schema.RequiredMode.REQUIRED)
@Column(name = "order_num", columnDefinition = "int(10) not null COMMENT '排序号'")
private Integer orderNum;
@TableLogic
@JsonIgnore
@Column(name = "del_flag", columnDefinition = "int(2) not null COMMENT '删除状态:0-正常,1-删除'")
@TableField(value = "del_flag", fill = FieldFill.INSERT)
private Integer delFlag;
// ---------------------- 以下非数据库字段 ----------------------
@Schema(description = "子孩子", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@TableField(exist = false)
@Transient
private List<SysMenu> children;
/**
* 建树
*
* @param list 待建树集合
* @param parentId 父节点,一般为0作为父节点
* @return 返回树
*/
public static List<SysMenu> streamToTree(List<SysMenu> list, Integer parentId) {
return list.stream()
.filter(parent -> Objects.equals(parent.getParentId(), parentId))
.peek(child -> child.setChildren(streamToTree(list, child.getId())))
.collect(Collectors.toList());
}
}
2.2 涉及BaseModel
类
package cn.keyidea.common.bean;
import cn.keyidea.common.valid.GroupChangePwd;
import cn.keyidea.common.valid.GroupCustomWithId;
import cn.keyidea.common.valid.GroupUpdate;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* 实体父类
* <p>
* 特殊说明:
* 继承此基类的实体类,如果使用lombok的@Data注解时,主要同时添加@EqualsAndHashCode(callSuper = true)注解
* 1)注解@EqualsAndHashCode(callSuper = true),就是用自己的属性和从父类继承的属性来生成hashcode;
* 2)注解@EqualsAndHashCode(callSuper = false),就是只用自己的属性来生成hashcode;
* 3)@Data相当于@Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode这5个注解的合集, 和@EqualsAndHashCode默认是false。
* <p>
* MappedSuperclass注解说明:
* 1.@MappedSuperclass注解仅仅能标准在类上;这个注解标识在父类上面的,用来标识父类
* 2.标注为@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,可是他的属性都将映射到其子类的数据库字段中
* 3.标注为@MappedSuperclass的类不能再标注@Entity或@Table注解
* <p>
* EntityListeners注解及相关说明:
* EntityListeners:该注解用于指定Entity或者superclass上的回调监听类
* AuditingEntityListener:这是一个JPA Entity Listener,用于捕获监听信息,当Entity发生持久化和更新操作时
*
* @author qyd
* @date 2022-10-17
*/
@SuperBuilder // @SuperBuilder支持对基类成员属性的构造;如果子类继承了BaseModel,也需要使用该注解
@AllArgsConstructor // 全参构造函数
@NoArgsConstructor // 空参构造函数
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Schema(name = "BaseModel", description = "实体父类")
public class BaseModel implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@NotNull(message = "ID不能为NUll", groups = {GroupUpdate.class, GroupChangePwd.class, GroupCustomWithId.class})
@Schema(description = "主键ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@Id
@Column(name = "id", columnDefinition = "int(10) COMMENT '自增长ID'")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "create_time", updatable = false, columnDefinition = "datetime not null COMMENT '创建时间'")
@TableField(value = "create_time", fill = FieldFill.INSERT)
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@Schema(description = "创建人ID", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "create_by", updatable = false, columnDefinition = "int(10) not null COMMENT '创建人ID'")
@TableField(value = "create_by", fill = FieldFill.INSERT)
private Integer createBy;
@Schema(description = "更新时间", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "update_time", columnDefinition = "datetime COMMENT '更新时间'")
@TableField(value = "update_time", fill = FieldFill.UPDATE)
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
@Schema(description = "更新人ID", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@Column(name = "update_by", columnDefinition = "int(10) COMMENT '更新人ID'")
@TableField(value = "update_by", fill = FieldFill.UPDATE)
private Integer updateBy;
}
3.方式一 vs 方式二
比较项 | 方式一 | 方式二 |
---|---|---|
简洁度 | 良 | 优 |
是否支持对象原生字段 | 良 | 优 |
是否需要新增字段 | 部分 | 少 |
是否有冗余字段 | 存在 | 少 |
是否需要新建方法 | 不需要 | 需要 |
对于方式二来说,新增的字段主要就是在原生对象中新增
private List<T> children;
, 然后新增静态方法streamToTree
,并且能完美支持原生所有字段,所差的是,如果有10个类都需要建树的话,那么每个类都需要写同样的方法。不过对于方式一来说,如果真存在10个类,并且每个类字段都存在差异性,那么方式一中的TreeNode的冗余字段将变的非常之多。