I have an entity class Foo foo that contains Collection<Bar> bars. I’ve tried a variety of ways, but I’m unable to successfully update my collection.
One attempt:
foo = em.find(key);
foo.getBars().clear();
foo.setBars(bars);
em.flush; \\ commit, etc.
This appends the new collection to the old one.
Another attempt:
foo = em.find(key);
bars = foo.getBars();
for (Bar bar : bars) {
em.remove(bar);
}
em.flush;
At this point, I thought I could add the new collection, but I find that the entity foo has been wiped out.
Here are some annotations.
In Foo:
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "foo")
private List<Bar> bars;
In Bar:
@ManyToOne(optional = false, cascade = { CascadeType.ALL })
@JoinColumn(name = "FOO_ID")
private Foo foo;
Has anyone else had trouble with this? Any ideas?
The second approach would work if you remove
CascadeType.ALLfromprivate Foo fooand callfoo.getBars().clear()after removingBars.Currently, when you remove
Bars in your second approach, removal is propagated to the correspondingFooentity, becauseCascadeType.ALLincludesCascadeType.REMOVE.