猿问

查询多级商品分类怎么依次显示到页面上?

正在做一个商城项目,被商品分类的分级查询给难住了,sql语句我倒是写出来了,可是不知道怎么保存在Java对象里,我使用的是SpringBoot,mybatis,freemarker,mysql。
数据表结构:
CREATETABLEgoods_type
(
typeIdINTPRIMARYKEYAUTO_INCREMENT,
typeNameVARCHAR(255)NOTNULL,
typeDescLONGTEXTNOTNULL,
typeParentintREFERENCESgoods_type(typeId)//上一级分类,最顶层为0
)CHARSETutf8
查询语句:
selectl1.typeIdas一级菜单编号,l1.typeNameas一级菜单名称,l1.typeDescas1描述,
l2.typeIdas二级菜单编号,l2.typeNameas二级菜单名称,l2.typeDescas2描述,
l3.typeIdas三级菜单编号,l3.typeNameas三级菜单名称,l3.typeDescas3描述
fromgoods_typel1
innerJOINgoods_typel2ONl1.typeId=l2.typeParent
innerJOINgoods_typel3onl3.typeParent=l2.typeId;
请问怎么保存在Java对象中,从而显示到页面。
湖上湖
浏览 835回答 2
2回答

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"}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答