递归删除资源树

前言

  • 最近项目里有这么一个需求:现在有一个用Ztree编写的资源树,当删除资源树的某个节点时,则将此节点下面的所有节点全部删除,这里显然就用到了递归;若此节点被删除后无其它的兄弟节点了,我们还需要将其父节点更新成新的子节点。

代码中用到的技术

  • 小编操作数据库用的是mybatis,大部分操作直接使用的mybatis的逆向工程,至于mapper的注入,我就不贴代码了。

1、删除节点的入口

public void deleteCategory(Long id) {
    //将此节点对象从数据库中搜出来
    TbContentCategory node = categoryMapper.selectByPrimaryKey(id);
    //删除此节点
    this.recursiveDelete(id);
    //判断是否更新父节点
    this.updateParentNode(node.getParentId());
}

2、递归删除资源树上的节点

/**
 * 递归删除资源树上的节点
 * @param 要删除的节点id
 */
public void recursiveDelete(Long id) {
    // 查询此节点下面的所有的子节点
    List<TbContentCategory> list = getListByParentId(id);
    // 若此节点下面没有子节点
    if (list.size() == 0) {
        TbContentCategory deleteNode = categoryMapper.selectByPrimaryKey(id);
        //得到此节点的父节点Id
        Long parentId = deleteNode.getParentId();
        //删除此节点
        categoryMapper.deleteByPrimaryKey(id);
        //删除此节点后,判断此节点的父节点是否为子节点,若是,则更新其父节点为子节点
        this.updateParentNode(parentId);
    } else {
        categoryMapper.deleteByPrimaryKey(id);
        for (TbContentCategory category : list) {
            if (category.getIsParent()) {
                //递归删除节点
                this.recursiveDelete(category.getId());
            } else {            categoryMapper.deleteByPrimaryKey(category.getId());
            }
        }

    }
}

3、删除子节点后,判断其父节点是否需要更新成子节点

/**
 * 判断此节点是否存在兄弟节点,若不存在,则将其父节点更新成子节点
 * @param 节点Id
 */
private void updateParentNode(Long parentId) {
    //查询此节点的所有的兄弟节点
    List<TbContentCategory> contentCat = getListByParentId(parentId);
    //若无兄弟节点
    if (contentCat.size() == 0) {
        //更新此节点的父节点为子节点
        TbContentCategory node2 = categoryMapper.selectByPrimaryKey(parentId);
        node2.setIsParent(false);
        categoryMapper.updateByPrimaryKeySelective(node2);
    }
}

4、根据父节点Id 查询所有的兄弟节点

/**
 * 根据父节点Id 查询所有的兄弟节点
 * @param parentId
 * @return
 */
public List<TbContentCategory> getListByParentId(Long parentId) {
    TbContentCategoryExample example = new TbContentCategoryExample();
    Criteria criteria = example.createCriteria();
    criteria.andParentIdEqualTo(parentId);
    List<TbContentCategory> list = categoryMapper.selectByExample(example);
    return list;
}

小结

  • 上面便是大体的业务逻辑,当然,读者还可以根据自己的需求更改成适应自己项目的业务逻辑。
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值