ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

融资项目——获取树形结构的数据

融资项目——获取树形结构的数据

如下图所示,下列数据是一个树形结构数据,行业中包含若干子节点。表的设计如下图,设置了一个id为1的虚拟根节点。(本树形结构带虚拟根节点共三层)

实现逻辑:

延时展示方法,先展现第二层的信息,如果想要看到具体第三层的信息,点击按钮触发后台请求,通过当前点击的父节点获得其所有子节点。

实现方法:

0. 首先在Dict实体类中加入如下属性:

 @TableField(exist = false)//逻辑概念的属性,与物理表没有关系,数据库表中不存在该字段。private boolean hasChildren;

1.Service层:

    @Overridepublic List<Dict> listByParentId(Long parentId) {QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();queryWrapper.eq("parent_id",parentId);List<Dict> dictList= dictMapper.selectList(queryWrapper);//填充hasChildren字段dictList.forEach(dict -> {//判断当前字段是否有子节点dict.setHasChildren(this.hasChildre(parentId));});return dictList;}//    判断当前节点下是否存在子节点private  boolean hasChildre(Long id){QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();queryWrapper.eq("parent_id",id);Integer count=dictMapper.selectCount(queryWrapper);if(count>0)return true;else return false;}

2. Controller层:

@ApiOperation("根据上级id获取所有子节点信息")@GetMapping("/listByParentId/{parentId}")public R listByParentId(@ApiParam(value = "上级父节点的id")@PathVariable Long parentId){List<Dict> dictList=dictService.listByParentId(parentId);return R.ok().data("list",dictList);}

返回列表