Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA clear collection and add new items

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);
like image 949
Dennis Thrysøe Avatar asked Jul 13 '14 15:07

Dennis Thrysøe


2 Answers

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.

Mind the unique constraints

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.

like image 144
Vlad Mihalcea Avatar answered Oct 11 '22 14:10

Vlad Mihalcea


Turns out that the actual solution was using a @JoinColumn annotation instead of the mappedBy="" parameter.

like image 35
Dennis Thrysøe Avatar answered Oct 11 '22 13:10

Dennis Thrysøe