一般我们直接通过递归的方式就返回一个三级联动效率很高
大家可以参考这篇文章
省市县三级数据联动 -Java
我这边呢直接用三层for循环解决的速度很慢的400条1.73秒
为什么不用上面那个呢:因为是递归的思想最后一层还有多返回一个cityVOList[],前端这边node.js版本太低解决不了这个问题,所以就丢给后端处理了
[
{
"code": "1",
"nameZh": "中国",
"name": "中国",
"nameEn": "China",
"parentId": "0",
"cityVOList": [
{
"code": "4",
"nameZh": "安徽",
"name": "安徽",
"nameEn": "Anhui",
"parentId": "1",
"cityVOList": [
{
"code": "53",
"nameZh": "安庆市",
"name": "安庆市",
"nameEn": "Anqing",
"parentId": "4",
"cityVOList": []
}
]
}
]
}
]
// 获取第一层
List<Map<String, Object>> maps1 = dropdownMapper.city1(map);
List<Map<String, Object>> listMap = new ArrayList<>();
for (Map<String, Object> map1 : maps1) {
Map<String,Object> list = new HashMap<>();
String id = (String) map1.get("code");
list.put("code",map1.get("code"));
list.put("parentId",map1.get("parentId"));
list.put("name",map1.get("name"));
list.put("nameZh",map1.get("nameZh"));
list.put("nameEn",map1.get("nameEn"));
// 获取第二层
List<Map<String, Object>> maps2 = dropdownMapper.city2(id);
List<Map<String,Object>> list1 = new ArrayList<>();
for (Map<String, Object> map2 : maps2) {
String id2 = (String) map2.get("code");
Map<String,Object> list4 = new HashMap<>();
list4.put("code",map2.get("code"));
list4.put("parentId",map2.get("parentId"));
list4.put("name",map2.get("name"));
list4.put("nameZh",map2.get("nameZh"));
list4.put("nameEn",map2.get("nameEn"));
list1.add(list4);
// 获取第三层
List<Map<String, Object>> maps3 = dropdownMapper.city3(id2);
List<Map<String,Object>> list3 = new ArrayList<>();
for (Map<String, Object> map3 : maps3) {
Map<String,Object> list5 = new HashMap<>();
list5.put("code",map3.get("code"));
list5.put("parentId",map3.get("parentId"));
list5.put("name",map3.get("name"));
list5.put("nameZh",map3.get("nameZh"));
list5.put("nameEn",map3.get("nameEn"));
list3.add(list5);
}
list4.put("cityVOList",list3);
}
list.put("cityVOList",list1);
listMap.add(list);
}
[
{
"code": "1",
"nameZh": "中国",
"name": "中国",
"nameEn": "China",
"parentId": "0",
"cityVOList": [
{
"code": "4",
"nameZh": "安徽",
"name": "安徽",
"nameEn": "Anhui",
"parentId": "1",
"cityVOList": [
{
"code": "53",
"nameZh": "安庆市",
"name": "安庆市",
"nameEn": "Anqing",
"parentId": "4"
}
]
}
]
}
]
返回的为一个[name,code,city1[name,code,city2[]]]三层嵌套,进行三层for循环第一层为查询的顶级父类,拿到父类的code然后去查询该父类下面的数据,拿到后再进行查询一共三次当然这里看你是几级联动。