首先看一下表结构:
需求:
根据 id 删除当前内容(判断当前父节点下是否还有子节点;如果没有则需要更改父类 is_parent=0 变成子节点)(如果有就不要更新)
根据 id 删除当前内容时,如果是一个父节点 同时也需要删除所有的子节点。
如下关键代码:递归实现...
@Override
public TaotaoResult deleteByPrimaryKey(Long id) {
//01、首先查询要删除的对象信息
TbContentCategory category = tbContentCategoryMapper.selectByPrimaryKey(id);
if (category.getParentId() == 0) {
return new TaotaoResult(-1, "不能删除根节点", null);
}
tbContentCategoryMapper.deleteByPrimaryKey(category.getId());
//02、查询是否还有子节点,如果没有则把父节点改变成子节点
TbContentCategoryExample example = new TbContentCategoryExample();
example.createCriteria().andParentIdEqualTo(category.getParentId());
//返回的子节点集合信息
List<TbContentCategory> tbContentCategories = tbContentCategoryMapper.selectByExample(example);
if (null == tbContentCategories && tbContentCategories.size() == 0) {
//将父节点变成子节点
TbContentCategory category1 = new TbContentCategory();
category1.setId(category.getParentId());
category1.setIsParent(false);
category1.setUpdated(new Date());
tbContentCategoryMapper.updateByPrimaryKeySelective(category1);
}
//当前删除的对象信息要是父节点,则在进行递归删除
if (category.getIsParent()) {
del(category);
}
return TaotaoResult.ok();
}
/***
* 递归删除
* @param category
*/
private void del(TbContentCategory category) {
//01、判断是否为字节点还是父节点,子节点直接删除
if (category.getIsParent()) {
//02、查询出所有的子节点
TbContentCategoryExample example = new TbContentCategoryExample();
example.createCriteria().andParentIdEqualTo(category.getId());
List<TbContentCategory> tbContentCategories = tbContentCategoryMapper.selectByExample(example);
/***
* 1、首先是根据id 查询出所有的子节点 对象集合
* 2、利用循环遍历每一项,进行删除,同时把当前便利的对象 当作参数 再次调用删除方法
* 来判断此对象下是否还有子节点
*/
for (TbContentCategory item : tbContentCategories) {
tbContentCategoryMapper.deleteByPrimaryKey(item.getId());
del(item);
}
}
// if (category.getIsParent()) {
// tbContentCategoryMapper.deleteByPrimaryKey(category.getId());
// }
}