欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 递归查询树形菜单结构(个人认为是最简单的)

程序员文章站 2022-05-08 23:02:54
...
/**
	 * 获取无限级的类别资源
	 */
	@Override
	public List<Object> findTypeTree() throws BusinessException {
		Map<String,Object> map = new HashMap<>();
		map.put("EQ_parentId",0);
		Map<String, SearchFilter> filters = SearchFilter.parse(map);
		List<Order> orderList = new ArrayList<>();
		Order order = new Order("sortNum");
		orderList.add(order);
		Sort sort = new Sort(orderList);
		//默认查询出所有的一级类别
		List<TypeInfo> typeList = (List<TypeInfo>) typeInfoRepository.findAll(DynamicSpecifications.bySearchFilter(filters.values(), TypeInfo.class),sort);
		List<Object> list = new ArrayList<>();
		for (TypeInfo typeInfo : typeList) {
			JSONObject treeObject = new JSONObject(true);
			treeObject.put("id", typeInfo.getTypeId());
			treeObject.put("text", typeInfo.getName());
			treeObject.put("children", getChildren(typeInfo.getTypeId()));
			list.add(treeObject);
		}
		return list;
	}
	public List<Object> getChildren(Long parentId){
		List<Object> list = new ArrayList<>();
		List<TypeInfo> children = typeInfoRepository.findTypeInfoByParentIdAndSortNum(parentId);
		for (TypeInfo typeInfo : children) {
			if(parentId == typeInfo.getParentId()) {
				JSONObject obj = new JSONObject(true);
				obj.put("id", typeInfo.getTypeId());
				obj.put("text", typeInfo.getName());
				obj.put("children", getChildren(typeInfo.getTypeId()));
				list.add(obj);
			}
		}
		return list;
	}

 getChildren()方法传入一级类别的id 作为父id查询出其子类别,然后递归掉用getChildren()方法 实现树形菜单结构树

 

相关标签: 递归