前言
- 最近项目里有这么一个需求:现在有一个用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);
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;
}
小结
- 上面便是大体的业务逻辑,当然,读者还可以根据自己的需求更改成适应自己项目的业务逻辑。