views:

46

answers:

1

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?

+1  A: 

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.

axtavt
When I try that, I get:`javax.persistence.EntityNotFoundException: deleted entity passed to persist: [com.Bar#<null>]`
FarmBoy
@FarmBoy: You also should call `foo.getBars().clear()` after removing `Bar`s.
axtavt
It works now, thanks much.
FarmBoy