公司有个业务需要查出所有的用户权限分类,并将最后一层类别所包含的权限查出来。
数据库说明,有一个parent_id 字段是最好的:、
parent_id的值就是上级的id,一般的话,最顶级的parent_id是设置为0。
先看看表结构:
下面不说废话,直接上代码:
定义的vo类:
1
2
3
4
5
6
7
8
9
10
11
12
|
@ApiModelProperty ( "id" ) private Long id; @ApiModelProperty ( "父ID" ) private Long parentId; @ApiModelProperty ( "名称" ) private String name; @ApiModelProperty ( "子节点" ) private List<UserVo> children; |
获取列表
1
2
3
4
5
6
7
8
9
10
11
|
List<UserVo> userList userService.findUsersAndChildrenList(User); List<UserVo> users = new ArrayList<>(); for (UserVo r : userList) { UserVo user = new UserVo(); user.setId(r.getId()); user.setParentId(r.getParentId()); user.setName(r.getName()); List<UserVo> children = this .getChildrenList(r.getId(), status); user.setChildren(children); users.add(user); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public List<UserVo> getChildrenList(Long cid){ List<UserVo> users= userService.findUserChildrenByParentId(cid); List<UserVo> userList= new ArrayList<>(); if (users){ for (UserVo u : users) { UserVo user = new UserVo(); user.setId(u.getId()); user.setName(u.getName()); user.setParentId(u.getParentId()); List<UserVo > children = this .getChildrenList(u.getId()); user.setChildren(children); userList.add(user); } } return userList; } |
mybatis查询:
1
2
3
4
5
|
< select id = "findUserChildrenList" resultMap = "BaseResultMap" > SELECT * FROM user WHERE parent_id=#{id} </ select > |
最终的数据结构:
1
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
|
{ "message" : '获取成功' , "data" :{ "num" :1, "pageSize" :20, "total" :1, "list" :[ { "id" :6, "name" : "测试" , "parent_id" :1, "children" :[ { "id" :9, "name" : "测试1" , "parent_id" :6, "children" :[ { "id" :20, "name" : "测试2" , "parent_id" :9, "children" :[ { "id" :21, "name" : "测试3" , "parent_id" :20, }, { "id" :22, "name" : "测试4" , "parent_id" :20, }, { "id" :23, "name" : "测试5" , "parent_id" :20, } ], } ], }, ], } ] }, "code" :200 } |
如果要查某个节点的所有父节点:
mybatis查询改为 :
1
2
3
4
5
|
< select id = "findUserParentListById" resultMap = "BaseResultMap" > SELECT * FROM user WHERE id=#{id} </ select > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public List<UserVo> getParentList(Long cid){ List<UserVo> users= userService.findUserParentListById(cid); List<UserVo> userList= new ArrayList<>(); if (users){ for (UserVo u : users) { UserVo user = new UserVo(); user.setId(u.getId()); user.setName(u.getName()); user.setParentId(u.getParentId()); List<UserVo > children = this .getParentList(u.getParentId()); user.setChildren(children); userList.add(user); } } return userList; } |
到此这篇关于SpringBoot、mybatis返回树结构的数据实现的文章就介绍到这了,更多相关SpringBoot、mybatis返回树结构 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/lchmyhua88/article/details/124228470