最近开发中碰到需求,要根据指定id删除该id和其包含的所有子节点,下面简单分享一下
1.树形实体类
@Data
@Accessors(chain = true)
@TableName(value = "bulletin_dzh")
public class BulletinDzh {
@ApiModelProperty(value = "电子化id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "名称")
@TableField(value = "name")
private String name;
@ApiModelProperty(value = "父iD")
@TableField(value = "ppid")
private Integer ppid;
@ApiModelProperty(value = "内容")
@TableField(value = "document")
private String document;
@ApiModelProperty(value = "主表iD")
@TableField(value = "pid")
private Integer pid;
}
2.递归删除节点及其子节点(结合MybatisPlus框架)
@ApiOperation(value = "删除子节点", notes = "简报电子化")
@PostMapping("/delete/{id}")
@SysLog(value = "简报电子化删除子节点", type = LogTypeEnum.DELETE)
public ApiResult<Boolean> deleteBulletinDzh(@PathVariable("id") Integer id) {
//存储所有要删除的id
List<Integer> idList = new ArrayList<>();
//获得所有需要删除的id
this.selectChildListById(id, idList);
//添加删除的节点id
idList.add(id);
//MybatisPlus批量删除方法
int flag = bulletinDzhMapper.deleteBatchIds(idList);
if (flag > 0){
return ApiResult.ok();
}else {
return ApiResult.fail();
}
}
private void selectChildListById(Integer id, List<Integer> idList) {
//查询数据库pid等于id的数据
List<BulletinDzh> childList = bulletinDzhMapper.selectList(new
QueryWrapper<BulletinDzh>().eq("ppid", id).select("id"));
//递归查询下一级id,同时将上一次查询结果添加到list集合
childList.forEach(menu-> {
idList.add(menu.getId());
this.selectChildListById(menu.getId(), idList);
});
}
?
|