当前位置: 首页 > 工具软件 > pinyin-plus > 使用案例 >

mybatis-plus递归行政区划数据组装树型结构

端木令
2023-12-01

使用mybatis-plus实现,支持通过父级id查询所有子级;支持通过deep查询层级深度;

实体类

@Data
@TableName(value = "common_area")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonArea implements Serializable {
    private static final long serialVersionUID = 1745820721819717709L;

    @ApiModelProperty("id")
    private String id;

    @ApiModelProperty("父级id")
    private String pid;

    @ApiModelProperty("全id")
    private String extId;

    @ApiModelProperty("简称")
    private String name;

    @ApiModelProperty("全称")
    private String extName;

    @ApiModelProperty("拼音")
    private String pinyin;

    @ApiModelProperty("拼音首字母")
    private String pinyinPrefix;

    @ApiModelProperty("层级深度")
    private Integer deep;

    @TableField(exist = false)
    private List<CommonArea> children;
}

Service核心方法gitAreaByPid

@Service
public class CommonAreaServiceImpl extends ServiceImpl<CommonAreaMapper, CommonArea> implements CommonAreaService {
    @Override
    public List<CommonArea> gitAreaByPid(String pid, Integer deep) {
        return getAreaTree(this.list(), pid, deep);
    }

    /**
     * 通过pid递归组装树形结构
     * */
    static private List<CommonArea> getAreaTree(List<CommonArea> list, String id, Integer deep) {
        List<CommonArea> results = new ArrayList<>();
        list.forEach(v-> {
            if((StringUtils.isEmpty(deep) || v.getDeep() < deep) && v.getPid().equals(id) ) {
                List<CommonArea> children = getAreaTree(list, v.getId(), deep);
                List<CommonArea> repeatChildren = setFilterChildren(v.getName(), children, list, deep);
                if(repeatChildren.size() > 0) v.setChildren(repeatChildren);
                results.add(v);
            }
        });
        return results;
    }

    /**
     * 递归处理children中与当前项name相同时,将children中重复项的子项放到当前项children中
     * */
    static private List<CommonArea> setFilterChildren(String name, List<CommonArea> areaTree, List<CommonArea> list, Integer deep) {
        if(areaTree.size() > 0) {
            for (int i = 0; i < areaTree.size(); i++) {
                if(areaTree.get(i).getName().equals(name)) {
                    areaTree = getAreaTree(list, areaTree.get(i).getId(), deep);
                    areaTree = setFilterChildren(name, areaTree, list, deep);
                    areaTree.forEach(o-> o.setDeep(o.getDeep()-1));
                    break;
                }
            }
        }
        return areaTree;
    }
}
 类似资料: