jeck猫
mybatis的sql处理方式前面已经有答案了,不过个人不是很喜欢用复杂的sql来组装这种对象,sql就要尽量的简洁,只做数据的查询,像这种对象的处理封装还是交给程序控制的好。JDK8以前,我们做这种树形结构对象的封装一般都是递归处理,之后有了流处理,代码就可以更简洁了,随便写了个例子,无限层级的树形菜单,希望能帮到题主:@Testpublicvoidtest05(){//模拟创建数据Listlist=Arrays.asList(newGoodsType(0,"typeName0",null),newGoodsType(1,"typeName1",0),newGoodsType(2,"typeName2",1),newGoodsType(3,"typeName3",2),newGoodsType(4,"typeName4",3),newGoodsType(5,"typeName5",4));//根据父节点id分组Mapmap=list.stream().filter(o->Objects.nonNull(o.getTypeParent())).collect(Collectors.groupingBy(GoodsType::getTypeParent));//循环处理子节点构建树状结构list.forEach(goodsType->{if(map.containsKey(goodsType.getTypeId())){goodsType.setSubGoods(map.get(goodsType.getTypeId()));}});//获取指定节点的对象GoodsTyperesult=list.stream().filter(goodsType->goodsType.getTypeId()==0).findFirst().orElse(null);System.out.println(JSON.toJSONString(result,true));}树形对象只是原对象的基础上加了子节点list@Data@NoArgsConstructor@AllArgsConstructorpublicclassGoodsType{privateIntegertypeId;privateStringtypeName;privateStringtypeDesc;privateIntegertypeParent;privateListsubGoods;publicGoodsType(IntegertypeId,StringtypeName,IntegertypeParent){this.typeId=typeId;this.typeName=typeName;this.typeParent=typeParent;}}控制台打印:{"subGoods":[{"subGoods":[{"subGoods":[{"subGoods":[{"subGoods":[{"typeId":5,"typeName":"typeName5","typeParent":4}],"typeId":4,"typeName":"typeName4","typeParent":3}],"typeId":3,"typeName":"typeName3","typeParent":2}],"typeId":2,"typeName":"typeName2","typeParent":1}],"typeId":1,"typeName":"typeName1","typeParent":0}],"typeId":0,"typeName":"typeName0"}