后端业务层四层嵌套循环 查询所有数据后进入循环2,循环所有子数据
@Override
public List<CarTypeEntity> getCarTypeList() {//获取车类型list
CarTypeEntity carTypeEntity = new CarTypeEntity();
List<CarTypeEntity> carTypes = carTypeMapper.selectAll();//查询到数据库中所有数据
for (CarTypeEntity carType : carTypes) {//forEach增强for循环
if (carType.getParentId()==0){//判断是否最顶层类型
findChildren(carType,carTypes);//调用方法查找子类型
}
}
for (int i = carTypes.size()-1;i>0;i--){//循环所有的数据
if (carTypes.get(i).getParentId()!=0){//当获取到的不是顶层时
carTypes.remove(i);//因为已经在上方法把顶层的子类筛选出来,所以把不是顶层的删除
}
}
return carTypes;
}
查询子数据Children数组
private static void findChildren(CarTypeEntity carType, List<CarTypeEntity> carTypes) {
if (carType.getChildren()==null){//当首次运行时
carType.setChildren(new ArrayList<>());//给children赋ArrayList类型
}
for (CarTypeEntity type : carTypes) {//循环车类型集合查找当前类型子类型
if (type.getParentId().equals(carType.getId())&&type.getDeleteFlag()==0){//如果有类的parentId为当前类的Id时
List<CarTypeEntity> chiledren = carType.getChildren();//先获取当前类的children
chiledren.add(type);//把子类放进当前类的children里
carType.setChildren(chiledren);//然后set到当前类的children里
}
}
if (carType.getChildren().size()!=0){//判断是否拥有子类型 如果有子类的话,找子类的子类
List<CarTypeEntity> chiledren = carType.getChildren();//获取到当前类的所有children子类
for (CarTypeEntity type : chiledren) {//循环子类型调用方法查找子类型的子类型
findChildren(type,carTypes);//把当前children和所有数据放入方法进行筛选子类
}
carType.setChildren(chiledren);//把找到的子类放到当前子类里,实现加入子类的子类
}
}
Controller层返回发送JSON数据就可以接受
@GetMapping("listCarType")
public CommonResult lisCarType2(CarTypeEntity carTypeEntity){
List<CarTypeEntity> carTypeEntities = carTypeService.getCarTypeList();
return CommonResult.ok(carTypeEntities);
}
还有不明白的可以仔细看一下代码后端注释
还不明白可以评论提问
版权声明:本文为GSl0408原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。