分享知識-快樂自己:遞迴 遍歷刪除資訊
阿新 • • 發佈:2018-12-23
首先看一下表結構:
需求:
根據 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());
// }
}