在项目的实际开发中,肯定会遇到需要对组织架构树进行查询的业务场景,也就是多层的父子级关系查询
首先创建实体类
@Data
public class ExampleVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@ApiModelProperty(value = "id")
private Long id;
/**
* 父级id
*/
@ApiModelProperty(value = "父级id")
private Long parentId;
private List<ExampleVO> sons = new ArrayList<>();
}
然后写查询语句
select id,parent_id from example
最后写service层逻辑
@Override
public List<ExampleVO> onExamples() {
List<ExampleVO> exampleVOs = exampleMapper.onExamples();
ExampleVO exampleVO = new ExampleVO();
exampleVO.setId((long)0);
exampleVOs.add(exampleVO);
Map<Long, ExampleVO> map = exampleVOs.stream().collect(Collectors.toMap(ExampleVO::getId, s -> s));
for (ExampleVO exampleVO : exampleVOs) {
Long parentId = exampleVO.getParentId();
ExampleVO vo = null;
if (null != parentId && null != (vo = map.get(parentId))) {
List<ExampleVO> children = vo.getSons();
if (null == children) {
children = new ArrayList<>();
vo.setSons(children);
}
children.add(exampleVO);
}
}
List<ExampleVO> list = new ArrayList<>();
list.add(map.get((long)0));
return list;
}
可以根据需要,添加需要的字段,目前为了举例,只用了id和parent_id两个必须的字段

该博客介绍了如何在Java项目中处理组织架构的多层父子关系查询。通过创建实体类ExampleVO,定义id和parent_id字段,然后编写SQL查询语句获取数据。在Service层,利用stream进行数据处理,构建父子级联的树形结构。此方法适用于需要展示层级关系的业务场景。
3965

被折叠的 条评论
为什么被折叠?



