【问题标题】:How to get list of entities from list of Ids in springBoot?如何从 Spring Boot 中的 Id 列表中获取实体列表?
【发布时间】:2024-05-22 22:35:01
【问题描述】:

我的要求是从 ids 列表中获取实体列表,我正在尝试这样的事情,当我使用字符串方法时,我正在获取列表,但是当我尝试返回它时,它说不是找到了。

我的回购代码

  List<AddingProductForView> findAllByproductidIn(ArrayList<Integer> productid);

我的服务代码:-

   public List<AddingProductForView> getListOfData(ArrayList<Integer> productid){
        List<AddingProductForView> findAllByProductIdIn = repository.findAllByproductidIn(productid);
         return findAllByProductIdIn;
    }

我的控制器代码:-

    @PostMapping("/getProductsId")
public List<AddingProductForView> getListOfData(@RequestBody ArrayList<Integer> productid) {
    List<AddingProductForView> findAllByProductIdIn = fileService.getListOfData(productid);
    return findAllByProductIdIn;
}

在打印 toString 方法时(得到结果为:-

`[AddingProductForView [productid=1, productname=RO, imagepath=./assets/1.jpeg, price=4000  , productdescription=best], AddingProductForView [productid=2, productname=RO, imagepath=./assets/2.jpeg, price=8000  , productdescription=cheap], AddingProductForView [productid=3, productname=RO, imagepath=./assets/3.jpeg, price=2000  , productdescription=values]]`

我想从邮递员那里得到什么:-

  [1,3,2]

错误:- { "时间戳": "2021-07-02T07:25:50.973+0000", “状态”:404, “错误”:“未找到”, "message": "没有可用的消息", “路径”:“/api/excel/getProductsId” }

【问题讨论】:

  • 这里的实际问题是什么?
  • questionUpdated@rkosegi
  • 尝试将 {"productId":[1,2,3]} 放在邮递员请求正文中,您应该告诉我们您的问题是什么,以及您想做什么@DivyeshKumar
  • badRequest , QuestionUpdated @Dolphin
  • 试着把我告诉邮递员的东西@DivyeshKumar

标签: java spring spring-boot spring-mvc spring-data


【解决方案1】:

我们必须在方法级别使用@ResponseBody

@PostMapping("/getProductsId")
@ResponseBody
public List<AddingProductForView> getListOfData(@RequestBody List<Integer> productid) {
    List<AddingProductForView> findAllByProductIdIn = fileService.getListOfData(productid);
    return findAllByProductIdIn;
}

【讨论】:

  • 不,这东西不是必需的。因为在顶部,您提到了“@RestController”,它是“@Controller”和“@ResponseBody”的组合。
【解决方案2】:

您的控制器代码是:

@PostMapping("/getProductsByIds")

但是你在邮递员中输入的网址是:

"path": "/api/excel/getProductsId"

【讨论】:

  • 我在类级别定义了请求映射,如下所示:- @RequestMapping("/api/excel")
  • 我的意思是 getProductsByIdsgetProductsId
【解决方案3】:

只需将方法的签名:ArrayList 更改为接口 List

public List<AddingProductForView> getListOfData(@RequestBody List<Integer> productid)

【讨论】: