返回多个项目列表

时间:2021-01-01 18:01:35

标签: java

我想创建一个返回多个具有相同类别编号的项目的端点:

 @GetMapping("item/{product_item_id}")
    public ResponseEntity<ProductFullDTO> getCategoryDetail(@PathVariable("product_item_id") Integer productItemId) {

        Map<Integer, ProductFullDTO> categoriesList = categoriesService.getProductItemList();

        for (Map.Entry<Integer, ProductFullDTO> entry : categoriesList.entrySet()) {
            List<Integer> list = entry.getValue().getCategories();
            if (list.contains(productItemId)){
                return new ResponseEntity<ProductFullDTO>(entry.getValue(), HttpStatus.OK);
            }
        }

        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

DTO:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class ProductFullDTO {

    private int id;

    .........
    private List<Integer> categories;
}

数据:

public Map<Integer, ProductFullDTO> getProductItemList() {

        Map<Integer, ProductFullDTO> list = new HashMap<>();

        list.put(1, ProductFullDTO.builder().id(1).title("Classes for Busy Dads").productItemVideo(1).categories(List.of(1)).summary("Summary").build());
        list.put(2, ProductFullDTO.builder().id(2).title("Classes for Busy Moms").productItemVideo(2).categories(List.of(1)).summary("Summary").build());
        list.put(3, ProductFullDTO.builder().id(3).title("Classes for Busy Kids").productItemVideo(3).categories(List.of(2)).summary("Summary").build());

        return list;
    }

正如您在 ProductFullDTO 中看到的那样,我可以有多个 categories,但简而言之,我只能返回其中与 Rest API 请求中的参数匹配的 1 个。

你知道我怎样才能返回与 categories 编号匹配的多个项目吗?

1 个答案:

答案 0 :(得分:0)

所以,你需要做什么,就像@fantaghirocco 已经说过的,你需要:

  1. 创建一个 -loadView 列表并使您的函数返回该列表
  2. 在您的函数中,添加您想要返回到该列表的内容
  3. 返回该列表