简体   繁体   中英

Spring Boot Selecting then adding item to list

I am using Spring Boot for my API.

Here is my code: Here is my entity class:

    @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);
        }

    }

Here is my controller method:

    @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);
         });
     }

In my " addComponentToProductComponents " controller method, what I want to do is to select a product by id, which is what I am doing here:

var myProduct = myProductRepository.findById(productId);

then:

My Question :

How to add componentId to List < productComponents > after selecting the product by id?

your question not clear. myProduct is resulted by findById so cannot use with map ( the lambda function just go with collection) and the controller defines not correct. The controller should be like that:

 @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);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM