Java 选择Spring Boot,然后将项目添加到列表中
我正在为我的API使用Spring Boot 这是我的密码: 这是我的实体类:Java 选择Spring Boot,然后将项目添加到列表中,java,spring,spring-boot,spring-mvc,spring-data-jpa,Java,Spring,Spring Boot,Spring Mvc,Spring Data Jpa,我正在为我的API使用Spring Boot 这是我的密码: 这是我的实体类: @Table @Entity public class Product{ @Id @GeneratedValue private Long id; @ElementCollection private List<Long> productComponents = new ArrayList<&g
@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);
}
}
在我的“addComponentToProductComponents”控制器方法中,我要做的是按id选择产品,这就是我在这里所做的:
var myProduct = myProductRepository.findById(productId);
然后:
我的问题:
在按id选择产品后,如何将组件id添加到列表中?您的问题不清楚。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);
}
@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);
}