喵喔喔
mybatis的sql处理方式前面已经有答案了,不过个人不是很喜欢用复杂的sql来组装这种对象,sql就要尽量的简洁,只做数据的查询,像这种对象的处理封装还是交给程序控制的好。JDK8以前,我们做这种树形结构对象的封装一般都是递归处理,之后有了流处理,代码就可以更简洁了,随便写了个例子,无限层级的树形菜单,希望能帮到题主:
@Test
public void test05() {
//模拟创建数据
List<GoodsType> list = Arrays.asList(
new GoodsType(0, "typeName0", null),
new GoodsType(1, "typeName1", 0),
new GoodsType(2, "typeName2", 1),
new GoodsType(3, "typeName3", 2),
new GoodsType(4, "typeName4", 3),
new GoodsType(5, "typeName5", 4)
);
//根据父节点id分组
Map<Integer, List<GoodsType>> map = 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()));
}
});
//获取指定节点的对象
GoodsType result = list.stream().filter(goodsType -> goodsType.getTypeId() == 0).findFirst().orElse(null);
System.out.println(JSON.toJSONString(result, true));
}
树形对象 只是原对象的基础上加了子节点list
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GoodsType {
private Integer typeId;
private String typeName;
private String typeDesc;
private Integer typeParent;
private List<GoodsType> subGoods;
public GoodsType(Integer typeId, String typeName, Integer typeParent) {
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"
}