有一个需求是展示一个树形菜单的功能。之前的都是在mybatis层在<resultMap>
里面用<association>
关联查询处理,但是如果数据量大的话就有点慢,最近又发现一个递归的思想~~
这个是测试表结构
dao层就不贴出来啦~
业务层先查所有
@Override
public ResultData<List<Map>> selAll() {
ResultData<List<Map>> result = new ResultData<List<Map>>();
try{
List<Test> tests = businessSetMapper.findAll();
List<Map> mapList = findTree(tests, 0);
result.setData(mapList);
result.setCode(Sys_Constant.SUCCESS_CODE);
result.setMsg(Sys_Constant.SUCCESS_MSG);
} catch (Exception e) {
result.setCode(Sys_Constant.FAIL_CODE);
result.setMsg(Sys_Constant.FAIL_MSG);
e.printStackTrace();
} finally {
return result;
}
}
再调findTree方法放到map中,在children里面再递归调此方法~
public List<Map> findTree(List<Test> tests, Integer pId ){
List<Map> mapList = new ArrayList<>();
for (Test test : tests) {
if (test.getPId() != null && test.getPId().equals(pId)) {
Map map = new HashMap();
map.put("id",test.getId());
map.put("name",test.getName());
map.put("pId",test.getPId());
map.put("children",findTree(tests,test.getId() ) );
mapList.add(map);
}
}
return mapList;
}
postman测试
{
"code": "0000",
"data": [
{
"children": [
{
"children": [
{
"children": [],
"name": "男",
"pId": 2,
"id": 3
},
{
"children": [],
"name": "女",
"pId": 2,
"id": 4
}
],
"name": "性别",
"pId": 1,
"id": 2
},
{
"children": [
{
"children": [],
"name": "唱",
"pId": 5,
"id": 6
},
{
"children": [],
"name": "跳",
"pId": 5,
"id": 7
},
{
"children": [],
"name": "rap",
"pId": 5,
"id": 8
}
],
"name": "爱好",
"pId": 1,
"id": 5
}
],
"name": "分类",
"pId": 0,
"id": 1
}
],
"count": 0,
"msg": "请求成功!"
}
用这个的话只会查一次数据库,感觉比在xml层处理会好一点吧~~