mybatisplus简单生成树结构记录
1.Controller:
/**
* 区域树生成
* @return
*/
@GetMapping("/tree-list")
private Result regionTree() {
String stationCode = getStation().getStationTelecode();
List<StationRegionVo> tree = stationRegionListService.regionTree(stationCode);
return Result.ok(tree);
}
2.Service:
List<StationRegionVo> regionTree(String stationCode);
3.ServiceImpl:
@Override
public List<StationRegionVo> regionTree(String stationCode) {
// 1 查询全部数据
List<StationInfRelTree> stationInfRelTrees = stationRegionMapper.selectList(null);
// 2 查询所有一级节点
LambdaQueryWrapper<StationInfRelTree> wrapper = new LambdaQueryWrapper<StationInfRelTree>().eq(StationInfRelTree::getParentId, 1).eq(StationInfRelTree::getStationCode, stationCode);
List<StationInfRelTree> roots = stationRegionMapper.selectList(wrapper);
// 3 查询子节点
if (roots != null && !roots.isEmpty()) {
List<StationRegionVo> stationRegionRoots = new ArrayList<>();
roots.forEach(s -> {
StationRegionVo stationRegionVo = new StationRegionVo();
BeanUtils.copyProperties(s, stationRegionVo);
stationRegionRoots.add(stationRegionVo);
});
stationRegionRoots.forEach(r -> {
findChilds(r, stationInfRelTrees);
});
return stationRegionRoots;
}
return null;
}
// 添加子节点
private void findChilds (StationRegionVo regionVo, List<StationInfRelTree> all) {
List<StationRegionVo> children = new ArrayList<>();
all.forEach(s -> {
if (Objects.equals(s.getParentId(), regionVo.getRelaTreeId())) {
StationRegionVo stationRegionVo = new StationRegionVo();
BeanUtils.copyProperties(s, stationRegionVo);
children.add(stationRegionVo);
findChilds(stationRegionVo, all);
}
regionVo.setChildren(children);
});
}
4.mapper:
public interface StationRegionMapper extends BaseMapper<StationInfRelTree> {
}
5.Entity:
@Data
@TableName(value = "XXX")
public class StationInfRelTree implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id")
private String id;
@TableField("rela_tree_id")
private String relaTreeId;
@TableField("parent_id")
private String parentId;
}
5.Vo:
@Data
public class StationRegionVo implements Serializable {
private String id;
private String relaTreeId;
private String parentId;
...
private List<StationRegionVo> children;
}