使用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
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;
}
}