Problem updating collection using JPA
Posted
by FarmBoy
on Stack Overflow
See other posts from Stack Overflow
or by FarmBoy
Published on 2010-03-12T18:44:04Z
Indexed on
2010/03/12
18:47 UTC
Read the original article
Hit count: 219
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?
© Stack Overflow or respective owner