正在做一个商城项目,被商品分类的分级查询给难住了,sql语句我倒是写出来了,可是不知道怎么保存在Java对象里,我使用的是SpringBoot,mybatis,freemarker,mysql。
数据表结构:
CREATE TABLE goods_type
(
typeId INT PRIMARY KEY AUTO_INCREMENT,
typeName VARCHAR(255) NOT NULL ,
typeDesc LONGTEXT NOT NULL,
typeParent int REFERENCES goods_type(typeId) //上一级分类 ,最顶层为0
)CHARSET utf8
查询语句:
select l1.typeId as 一级菜单编号,l1.typeName as 一级菜单名称, l1.typeDesc as 1描述,
l2.typeId as 二级菜单编号,l2.typeName as 二级菜单名称,l2.typeDesc as 2描述,
l3.typeId as 三级菜单编号,l3.typeName as 三级菜单名称,l3.typeDesc as 3描述
from goods_type l1
inner JOIN goods_type l2 ON l1.typeId = l2.typeParent
inner JOIN goods_type l3 on l3.typeParent = l2.typeId;
请问怎么保存在Java对象中,从而显示到页面。
3 回答
喵喔喔
TA贡献1735条经验 获得超5个赞
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"
}
添加回答
举报
0/150
提交
取消