How to merge a @OneToMany relationship effectively?
For example I have the following two entity classes with a one-to-many relationship:
public class A implements Serializable {
...
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
private List<B> bs;
...
}
public class B implements Serializable {
...
@ManyToOne
private A a;
...
}
Suppose I have an instance of A
called a
, and a.bs == [b1, b2, b3]
. Now I want to remove b1
from, and add b4
to the relationship, so that a.bs == [b2, b3, b4]
, and b1.a == null
.
I've tried em.merge(a)
after doing a.setBs(b2, b3, b4)
, but that will result in a.bs == [b1, b2, b3, b4]
, unless I do an explicit b1.setA(null)
. However, this can lead to complexity if a.bs
changes a lot, and i开发者_开发百科f A
has more one-to-many relationships to other entity classes. Setting orphanRemoval = true
is also not the solution, because I simply want to set b1.a = null
instead of removing b1
.
This problem has been perplexing me for quit a long time, anybody that helps me out is greatly appreciated!
you can set cascade style to update on bs
and say
a.bs.remove(b1);
session.update(a);
this would do the trick.
you are telling the ORM to cascade updates on the collection, when you remove an entry from the collection, the corresponding value will be nullified.
精彩评论