Eric Wilson
Eric Wilson

Reputation: 59355

Problem updating collection using JPA

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?

Upvotes: 0

Views: 3874

Answers (1)

axtavt
axtavt

Reputation: 242686

The second approach would work if you remove CascadeType.ALL from private Foo foo and call foo.getBars().clear() after removing Bars.

Currently, when you remove Bars in your second approach, removal is propagated to the corresponding Foo entity, because CascadeType.ALL includes CascadeType.REMOVE.

Upvotes: 2

Related Questions