本文正在参加「技术专题19期 漫谈数据库技术」活动
前言
开发中树形结构应该是很常见的一种数据结构了。而在数据库方面往往也都伴随相应的树形设计。在 mysql 中通过 parent_id 来绑定其上游,从而达到树形结构的存储,但是在查询的过程中就需要我们将 List 列表转成我们理想中的 Tree 树。
构建树
List locations = this.baseMapper.selectList(queryWrapper);
Map collect = locations.stream().collect(Collectors.groupingBy(Location::getId));
List resultList = new ArrayList();
List parentLocation = getParentLocation(1, collect, id);
if (CollectionUtils.isNotEmpty(parentLocation)) {
for (Location location : parentLocation) {
QueryLocationDto dto = new QueryLocationDto();
BeanUtils.copyProperties(location, dto);
resultList.add(dto);
}
}
private List getParentLocation(int level, Map collect, String id) {
List locationList = new ArrayList();
if (collect.containsKey(id)) {
Location location = collect.get(id).get(0);
locationList.add(location);
String superid = location.getSuperid();
locationList.addAll(getParentLocation(level + 1, collect, superid));
}
return locationList;
}
相信大部分我们 都是通过 Java 来处理的。 其中 getParentLocation 就是用递归不断的去构建上下级关系。这种方式也是我比较推荐的,因为这样就把职责分的很清楚 Java 负责处理业务 ,数据库 就仅仅用来做数据的持久化,这也方便我们对数据库切换与升级。否则在更换其他数据库时还需要考虑是否支持递归属性。
public List getTree(List parentList , Map |