hi guys i have a problem i have two entities product and category i want to add a category and multiple product in the same form like that in this capture
this is my entity Category
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idcategory;
private String nom;
@JsonManagedReference("category")
@OneToMany(mappedBy = "category", fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE})
private List<Product> products= new ArrayList<>();
public void add(Product item) {
if (item != null) {
if (products == null) {
products= new ArrayList<>();
}
products.add(item);
item.setCategory(this);
}
}
}
and this is entity Product
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idproduct;
private String nom;
private Integer prix;
@JsonBackReference("category")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoryproduct", referencedColumnName = "idcategory")
private Category category;
}
and this is my controller
@RequestMapping(method = RequestMethod.POST)
public void addcategory(@RequestBody Category c) throws IOException {
List<Product> products = c.getProducts();
products.forEach(item -> c.add(item)
);
categorieRepository.save(c);
}
when i try to post a category and multiple product it shows this problem
java.util.ConcurrentModificationException\\r\\n\\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1513)\\r\\n\\tat com.example.users.controller.CategoryController.addcategory(CategoryController.java:46)\\r\\n\\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
i want to know whats wrong with my code and how to fix that guys
CodePudding user response:
You just need to save c, as it already contains everything to save. Ain't need no loop whatsoever. ConcurrentModificationException is when you alter entity while in for-loop. This question here would have helped you:
Hibernate throwing a ConcurrentModificationException
CodePudding user response:
List<Product> products = c.getProducts();
products.forEach(item -> c.add(item));
The problem is here. You are trying to iterate over the list and trying to add items to the same list. It is not possible. You can add a temporary list to add the items.
CodePudding user response:
i fix that i changed List to Set and i changed @Data annotation to @getter and @setter cuz i faced a new error (java.util.AbstractSet.hashCode) and it works now