摘要
数据库单表存储多级别数据,使用parent_id字段进行关联。
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.heifan.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import java.util.List;
import lombok.Data; import lombok.EqualsAndHashCode;
@Data @EqualsAndHashCode(callSuper = false) public class TestTreeNode implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO) private Integer id;
private Integer parentId;
private String nodeName;
}
|
测试用例,写法不规范,大家在开发过程中一定要规范开发!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.heifan.demo.domain.vo;
import com.heifan.demo.entity.TestTreeNode; import lombok.Data;
import java.util.List;
@Data public class TestTreeVO {
private Integer id;
private Integer parentId;
private String nodeName;
private List<TestTreeVO> childList; }
|
功能实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public Object treeById(Integer id) { List<TestTreeVO> testTreeVOS = testTreeNodeDao.selectAll(); List<TestTreeVO> testTreeNodeList = testTreeVOS.stream().filter(m -> m.getId().equals(id)).map( (m) -> { m.setChildList(getChildrens(m, testTreeVOS)); return m; } ).collect(Collectors.toList()); String s = JsonTool.beanToJson(testTreeNodeList); log.info(s); return Result.success(); }
private List<TestTreeVO> getChildrens(TestTreeVO root, List<TestTreeVO> all) { List<TestTreeVO> children = all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).map( (m) -> { m.setChildList(getChildrens(m, all)); return m; } ).collect(Collectors.toList()); return children; }
|