【问题标题】:Spring Boot Selecting then adding item to listSpring Boot 选择然后将项目添加到列表
【发布时间】:2021-08-01 00:03:43
【问题描述】:

我正在为我的 API 使用 Spring Boot。

这是我的代码: 这是我的 entity 类:

    @Table
    @Entity
    public class Product{
        @Id
        @GeneratedValue
        private Long id;

        @ElementCollection
        private List<Long> productComponents = new ArrayList<>();
        
        public void addProductComponent(Long myComponent){
              this.productComponents.add(myComponent);
        }

    }

这是我的控制器方法:

    @PostMapping("/components/add")
    public void addComponentToProductComponents(@PathVariable Long productId, @PathVariable Long componentId) throws ProductException {
         var myProduct = myProductRepository.findById(productId);
         myProduct.map((item) -> {
         item.addProductComponent(componentId);
         });
     }

在我的“addComponentToProductComponents”控制器方法中,我要做的是通过 id 选择产品,这就是我在这里所做的:

var myProduct = myProductRepository.findById(productId);

然后:

我的问题

通过id选择产品后如何将componentId添加到ListproductComponents>?

【问题讨论】:

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


    【解决方案1】:

    你的问题不清楚。 myProduct 是由 findById 导致的,因此不能与 map 一起使用(lambda 函数只与集合一起使用)并且控制器定义不正确。 控制器应该是这样的:

     @PostMapping("/products/{productId}/components/{componentId}/add")
     public void addComponentToProductComponents(@PathVariable Long productId, @PathVariable Long componentId) throws ProductException {
         var myProduct = myProductRepository.findById(productId);
         // logic add component
         // myProduct.getProductComponents().add(componentId);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多