I have a @OneToMany collection (list) that I would like to clear, and add new elements to in the same transaction.
Using
collection.clear();
collection.add(new EntityB());
Simply adds the new instance, and never removes anything. I have orphanRemoval = true
for the collection field.
ADDED:
// Parent entity
@OneToMany(mappedBy = "product", orphanRemoval = true)
private List<Feature> features = new ArrayList<>();
// Child entity
@ManyToOne(cascade = CascadeType.ALL)
private Product product;
// Clear and add attempt
product.getFeatures().clear();
Feature feature = new Feature(product, ls);
product.getFeatures().add(feature);
You try to clear only one side of the bidirectional association.
So instead of:
collection.clear();
Try clearing both sides and it should work:
for(Iterator<Feature> featureIterator = features.iterator(); featureIterator.hasNext(); ) { Feature feature = featureIterator .next(); feature.setProduct(null); featureIterator.remove(); }
Also, remove the cascade from @ManyToOne
and move it to @OneToMany
.
However, if you have a unique constraint, this clear + add
Anti-Pattern will not work since the INSERT action is executed before the DELETE one.
The proper way to do it is to check which entries need to be removed and just remove those. Then, add the new ones, and update the ones that got modified. This is how you do a collection merge properly.
Turns out that the actual solution was using a @JoinColumn annotation instead of the mappedBy="" parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With