前言
关于分类管理删除功能的实现在我学的淘淘商城作为作业任务完成的。自己想了会没实现就百度,然后我发现查到的结果几乎都是错的,根本不能实现完整的删除功能(删除当前节点和全部子节点,并在该节点的父节点不存在子节点时改父节点为子节点)。于是自己花了几个小时写了这删除功能,虽然花的时间比较久,但结果是好的,本人是新手刚学java
不久,留给有需要的人看。
Dao层
单表操作,可使用逆向工程
Service层
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
//创建子节点对象
private List<TbContentCategory> allNode = new ArrayList<>();
/**
* 获取当前id对应的节点下面的所有子节点(递归方法)
*/
private List<TbContentCategory> findAllNode(Long id){
//获取当前id所有次节点
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(id);
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
//遍历次节点
for (TbContentCategory tbContentCategory : list) {
//添加进子节点对象中
allNode.add(tbContentCategory);
//为父节点则递归
if(tbContentCategory.getIsParent()) {
Long childId = tbContentCategory.getId();
findAllNode(childId);
}
}
return allNode;
}
@Override
public TaotaoResult delectCategory(Long id) {
//通过id获取contencategory对象
TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
//判断是否是父节点
if (contentCategory.getIsParent()) {
//如果是父节点则调用findAllNode()方法获取全部子节点
List<TbContentCategory> allNode = findAllNode(id);
//遍历删除
for (TbContentCategory tbContentCategory : allNode) {
contentCategoryMapper.deleteByPrimaryKey(tbContentCategory.getId());
}
}
//为子节点则直接删除
contentCategoryMapper.deleteByPrimaryKey(id);
//更改父节点的isparent状态的实现
//获取该节点的父节点
TbContentCategory parentNode = contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
//通过父节点的id查询该父节点下的全部次级节点,即该节点的同级节点
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(parentNode.getId());
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
//如果同级节点不存在则改该节点的父级节点为子节点
if (list.size()==0) {
parentNode.setIsParent(false);
//更新
contentCategoryMapper.updateByPrimaryKey(parentNode);
}
return TaotaoResult.ok();
}
}
Controller层
@RequestMapping("/content/category")
@Controller
public class ContentCategoryController {
@Autowired
private ContentCategoryService cantenCategoryService;
@RequestMapping("/delete")
@ResponseBody
public TaotaoResult deleteNode(Long id) {
TaotaoResult result = cantenCategoryService.delectCategory(id);
return result;
}
}