@Service public class ContentCategoryServiceImpl extends BaseServiceImpl<ContentCategory> implements ContentCategoryService { @Override public void deleteContentCategory(Long parentId, Long id) { // 聲明存放需要刪除的節點的容器 List<Object> ids = new ArrayList<>(); // 把自己的id放到ids中 ids.add(id); // 使用遞歸獲取所有需要刪除的節點的id this.getIds(id, ids); // 使用父類的方法,批量刪除 super.deleteByIds(ids); // 查詢兄弟節點,聲明查詢條件 ContentCategory param = new ContentCategory(); param.setParentId(parentId); // 執行查詢 int count = super.queryCountByWhere(param); // 判斷是否沒有兄弟節點 if (count == 0) { // 如果沒有兄弟節點 ContentCategory parent = new ContentCategory(); parent.setId(parentId); // 修改父節點的isParent為false parent.setIsParent(false); // 執行修改 super.updateByIdSelective(parent); } // 如果還有兄弟節點,神馬都不做 } // 使用遞歸的方式查詢所有的子節點的id private void getIds(Long id, List<Object> ids) { // 根據條件查詢當前節點的所有的子節點 ContentCategory param = new ContentCategory(); param.setParentId(id); List<ContentCategory> list = super.queryListByWhere(param); // 使用遞歸的方式,必須設置遞歸的停止條件,否則會一直自己調用自己,直到內存溢出 // 判斷是否還有子節點 if (list.size() > 0) { // 如果有子節點,遍歷結果集 for (ContentCategory son : list) { // 1.把子節點的id放到ids容器中 ids.add(son.getId()); // 2.執行遞歸,自己調用自己,查詢子節點的子 this.getIds(son.getId(), ids); } } } }