项目中我们可能经常有这样的需求,需要返回二级、三级或者更多级的菜单,返回一个树形结构。这里采用地区表来演示。
数据库表及初始化数据
1 | -- ---------------------------- |
Area.java
1 | package com.vnext.pojo; |
AreaMapper.java
1 | public interface AreaMapper extends MyMapper<Area> { |
AreaService.java
1 |
|
AreaController.java
1 | "/area/{id}") ( |
AreaMapper.xml
1 |
|
api接口实现的json格式
http://localhost:8087/api/area/11
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78{
"code": 200,
"message": "SUCCESS",
"total": 1,
"data": {
"id": 1,
"areaName": "广东省",
"parentId": 0,
"childrenList": [
{
"id": 2,
"areaName": "深圳市",
"parentId": 1,
"childrenList": [
{
"id": 14,
"areaName": "深圳市罗湖区",
"parentId": 2,
"childrenList": []
}
]
},
{
"id": 3,
"areaName": "广州市",
"parentId": 1,
"childrenList": [
{
"id": 7,
"areaName": "番禺区",
"parentId": 3,
"childrenList": []
},
{
"id": 8,
"areaName": "天河区",
"parentId": 3,
"childrenList": [
{
"id": 9,
"areaName": "天河区街道1",
"parentId": 8,
"childrenList": [
{
"id": 11,
"areaName": "天河区街道1社区01",
"parentId": 9,
"childrenList": [
{
"id": 12,
"areaName": "天河区街道1社区01-D地块",
"parentId": 11,
"childrenList": [
{
"id": 13,
"areaName": "天河区街道1社区01-D地块A栋楼",
"parentId": 12,
"childrenList": []
}
]
}
]
}
]
},
{
"id": 10,
"areaName": "天河区街道2",
"parentId": 8,
"childrenList": []
}
]
}
]
}
]
}
}
小结
这种递归的方式可以实现无极限的树形结构,但是递归的方式性能会比较差。
如果业务系统很明确有几级,那就直接写几级,也就是写几个 resultMap。