在项目的实际开发中,肯定会遇到需要对组织架构树进行查询的业务场景,也就是多层的父子级关系查询
首先创建实体类
@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两个必须的字段