1.地区树形结构
/**
* 地区树形结构
* @author xzx
* @date 2021/12/21 16:47
*/
public class DistrictVo {
private String code;
private String parentCode;
private String name;
private List<DistrictVo> chridrenList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getParentCode() {
return parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
public List<DistrictVo> getChridrenList() {
return chridrenList;
}
public void setChridrenList(ArrayList<DistrictVo> chridrenList) {
this.chridrenList = chridrenList;
}
}
2.查询地区集合
public List<DistrictVo> treeDistrictByOrgCode(String orgCode) {
List<DistrictVo> districtVos = sysTDistrictMapper.treeDistrictByOrgCode(orgCode);
if (!CollectionUtils.isEmpty(districtVos)){
if (!Objects.equals("00",districtVos.get(0).getParentCode())){
districtVos.get(0).setParentCode("00");
}
}
return this.buildTreeDistrict(districtVos);
}
3.sql
select code,parent_code as parentCode, name from sys_t_district where code like concat(#{orgCode},'%') and level in ("1","2","3","4")
4.构建树结构
private List<DistrictVo> buildTreeDistrict(List<DistrictVo> districtVos) {
List<DistrictVo> trees = new ArrayList<DistrictVo>();
for (DistrictVo treeNode : districtVos) {
if ("00".equals(treeNode.getParentCode())) {
trees.add(findChildren(treeNode,districtVos));
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes
* @return
*/
public DistrictVo findChildren(DistrictVo treeNode,List<DistrictVo> treeNodes) {
//treeNode.setChridrenList(new ArrayList<DistrictVo>());
for (DistrictVo it : treeNodes) {
if(treeNode.getCode().equals(it.getParentCode())) {
if (treeNode.getChridrenList() == null) {
treeNode.setChridrenList(new ArrayList<DistrictVo>());
}
treeNode.getChridrenList().add(findChildren(it,treeNodes));
}
}
return treeNode;
}