项目需求:上级代理商可以看到自己和下级代理商
方案:利用树形查询,递归实现
数据库表:
每一行都有id和推荐人id,实现输入name查询本身与下级
Service层的实现
@Override
public List<DlsUserTreePO> treeList(int id) {
List<DlsUserPO> menuList = list();
List<DlsUserTreePO> result = menuList.stream()
.filter(menu -> menu.getRefereeId().equals(id))
.map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
return result;
}
@Override
public List<DlsUserTreePO> treeList() {
List<DlsUserPO> menuList = list();
List<DlsUserTreePO> result = menuList.stream()
.filter(menu -> menu.getRefereeId().equals(0))
.map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
return result;
}
/**
* 将UmsMenu转化为UmsMenuNode并设置children属性
*/
@Override
public DlsUserTreePO covertMenuNode(DlsUserPO menu, List<DlsUserPO> menuList) {
DlsUserTreePO node = new DlsUserTreePO();
BeanUtils.copyProperties(menu, node);
List<DlsUserTreePO> children = menuList.stream()
.filter(subMenu -> subMenu.getRefereeId().equals(menu.getId()))
.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
node.setChildUser(children);
return node;
}
实体类
public class DlsUserTreePO extends DlsUserPO {
private List<DlsUserTreePO> childUser;
}
Controller层
@RequestMapping("/treeQuery/{name}")
@ApiOperation(value = "树形查询推荐人",httpMethod = "POST")
public R<?> treeQuery(@PathVariable("name") String name){
int id=dlsUserMapper.selectByName(name);
DlsUserTreePO dlsUserTreePO=dlsUserService.itself(id);
List<DlsUserTreePO> dlsUserTreePOS=dlsUserService.treeList(id);
dlsUserTreePO.setChildUser(dlsUserTreePOS);
return R.ok(dlsUserTreePO,"查询成功");
}
@RequestMapping("/treeQuery")
@ApiOperation(value = "生成树形",httpMethod = "POST")
public R<?> treeQuery(){
List<DlsUserTreePO> dlsUserTreePOS=dlsUserService.treeList();
return R.ok(dlsUserTreePOS,"查询成功");
}
返回的结果:
|