菜单递归调用

该博客介绍了如何使用Java实现菜单数据的递归遍历,通过创建对象模型`ItemCat`和`ItemCatResult`,以及在`ItemCatServiceImpl`服务中定义递归方法`getItemCatList`,查询并构建多级菜单。通过对数据库查询的结果进行遍历和条件判断,将父节点和子节点分别处理,最终形成包含层级信息的菜单列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.数据格式


2.对象模型


public class ItemCat {

//转换成json数据时使用u作为key

@JsonProperty("u")

private String url;

@JsonProperty("n")

private String name;

@JsonProperty("i")

private List<?> item;

}


public class ItemCatResult {

private List<?> data;

 

public List<?> getData() {

return data;

}

 

public void setData(List<?> data) {

this.data = data;

}

}


3.service逻辑处理

@Service

public class ItemCatServiceImpl implements ItemCatService {

 

@Autowired

private TbItemCatMapper itemCatMapper;

@Override

public ItemCatResult queryAllCategory() throws Exception {

ItemCatResult result = new ItemCatResult();

result.setData(getItemCatList(0l));

return result;

}

/**

 * 查询分类列表

 * <p>Title: getItemCatList</p>

 * <p>Description: </p>

 * @param parentid

 * @return

 */

private List<?> getItemCatList(long parentid) {

TbItemCatExample example = new TbItemCatExample();

Criteria criteria = example.createCriteria();

//查询parentid0的分类信息

criteria.andParentIdEqualTo(parentid);

List<TbItemCat> list = itemCatMapper.selectByExample(example);

List dataList = new ArrayList();

for (TbItemCat tbItemCat : list) {

//判断是否为父节点

if (tbItemCat.getIsParent()) {

ItemCat itemCat = new ItemCat();

itemCat.setUrl("/category/" + tbItemCat.getId() + ".html");

itemCat.setName(tbItemCat.getName());

//递归调用

itemCat.setItem(getItemCatList(tbItemCat.getId()));

//添加到列表

dataList.add(itemCat);

} else {

String catItem = "/item/" + tbItemCat.getId() + ".html|" + tbItemCat.getName();

dataList.add(catItem);

}

}

return dataList;

}

 

}

注:代码可能对大家帮助不大,因为毕竟数据库设计的不一样,但查询思路差别不大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值