spring删除父节点及其所有子节点
作者:互联网
service
public void deleteCategoriesById(Long id,Long pid) {
//获取对象
Category category1 = this.categoryMapper.selectByPrimaryKey(id);
//创建子对象的id的列表
List<Long> sons = new ArrayList<>();
//创建中间列表
List<Long> temp = new ArrayList<>();
//判断是否是父节点
if (category1.getIsParent()) {
//若是父节点
Example example = new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("parentId", id);
//删除本节点
this.categoryMapper.deleteByPrimaryKey(id);
while (true) {
//获取所有子对象列表
List<Category> categories = this.categoryMapper.selectByExample(example);
//遍历子节点列表
for (Category category2 : categories) {
//判断子节点是否为父节点
if (category2.getIsParent()) {
temp.add(category2.getId());
}
//将所有需要删除的id放入sons中
sons.add(category2.getId());
}
// 此处如果使用增强for循环,会报ConcurrentModificationException,
// 因为增强for循环也是通过Iterator实现的,使用List的remove方法会与Iterator产生冲突
// for (Long son:sons){
// this.categoryMapper.deleteByPrimaryKey(son);
// sons.remove(son);
// }
//遍历,获取子对象id
Iterator<Long> iterator = sons.iterator();
while (iterator.hasNext()) {
Long son = iterator.next();
this.categoryMapper.deleteByPrimaryKey(son);
iterator.remove();
}
//如果子节点还有子节点
if (temp.size() > 0) {
sons=temp;
temp = new CopyOnWriteArrayList<Long>();
} else {
break;
}
}
}
//若不是父节点,判断其父节点是否只剩一个子,如果只剩一个,则将父节点isparent改为false
this.categoryMapper.deleteByPrimaryKey(id);
Category category3 = new Category();
category3.setParentId(pid);
List<Category> list = this.categoryMapper.select(category3);
//list.forEach(System.out::println);
if (list.isEmpty()){
Category category = new Category();
category.setId(pid);
category.setIsParent(false);
this.categoryMapper.updateByPrimaryKeySelective(category);
}
}
pojo
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Long parentId;
private Boolean isParent;
private Integer sort;
//get、set
}
代码比较冗余,之后再改
标签:Category,删除,spring,Long,id,categoryMapper,sons,节点 来源: https://blog.csdn.net/madaooadam/article/details/100108686