循环递归查询

134 阅读1分钟

最近工作中遇到需要查询类似树状数据的问题,经过思索想到的方法是循环递归查询,就是在遍历的时候进行递归。查询效率的话相对比较低,但是业务对这方面要求不高,因为是夜间定时执行的。还请大家多多指教。。。

1651320017(1).jpg 数据的形式的话如上图;A作为一个root节点,有可能向左或者向右有数据发散,根据我们这边的业务的话就是左边的称为上游,右边的称为下游。 有两张表,一张是详细数据表,一张是关系表

public static void main(String[] args) {
    List<ResultDto> result = new ArrayList<>();
    List<String> ids = new ArrayList<>(); // 为了防止出现循环查询
    String queryId = "111";
    List<ResultDto> collDtos = queryData(queryId, result, ids);
}

@Data
public class ResultDto implements Serializable {
    private String sorId;
    private String sorName;
    private String tarId;
    private String tarName;
}


@Data
public class RelDto implements Serializable {
    private String sorId;
    private String tarId;
}


@Data
public class CollDto implements Serializable {
    private String id;
    private String name;
}


public static List<ResultDto> queryData(String id, List<ResultDto> result, List<String> ids) {
    String sql = "SELECT SORID,TARID FROM REL_TAB";
    List<RelDto> relDtos = relMapper.selectUp(id);
    for (RelDto relDto : relDtos) {
        ResultDto resultDto = new ResultDto();
        resultDto.setTarId(relDto.getTarId());
        CollDto collDto = collMappper.selctOneById(relDto.getSorId());
        resultDto.setTarId(collDto.getId());
        resultDto.setTarName(collDto.getName());
        result.add(resultDto);
        ids.add(relDto.getSorId());
        queryData(relDto.getSorId(), result, ids);
    }
    return result;
}