Hi,
I'm not sure how to solve the following problem. Maybe you can help me.
I have a OneToMany association (bidirectional) between to classes which looks like this
Code:
class Parent {
...
/*** 1:n Child***/
@OneToMany(targetEntity = Child.class, fetch = FetchType.LAZY, mappedBy = "parent")
@Cascade( { org.hibernate.annotations.CascadeType.ALL })
@Fetch(FetchMode.SELECT)
private Set<Child> children;
public void setChildren(Set<Child> children) {
// remove all existing children
if (this.children!= null && !this.children.isEmpty()) {
for (Child child: this.children) {
child.setParent(null);
}
this.children.clear();
}
// add new children
for (Child child : children) {
child.setParent(this);
if (!this.children.contains(child)) {
this.children.add(child);
}
}
}
}
Code:
class Child {
...
/*** n:1 Parent***/
@ManyToOne(targetEntity = Parent.class, fetch = FetchType.LAZY)
private Parent parent;
}
When I want to set new children to the parent, I use the method setChildren in my service class and then saveParent:
Code:
@Transactional
public void setChildren(Parent parent, Child... children) {
parent.setChildren(new HashSet<Folder>(Arrays.asList(children)));
}
@Transactional
public void saveParent(Parent parent) {
getCurrentSession().saveOrUpdate(parent);
}
I have a problem with overwriting existing children.
Assuming Parent A already exists with two children 1 und 2. When I now call setChildren with two new children (3, 4) and save the Parent afterwards, the children 1 and 2 are still associated with the Parent. Here my test code:
Code:
Parent parent_A = manager.createParent("A");
manager.saveParent(parent_A);
Child child_1 = manager.createChild("1");
Child child_2 = manager.createChild("2");
Child child_3 = manager.createChild("3");
Child child_4 = manager.createChild("4");
// set 1 and 2 to A
manager.setChildren(parent_A, child_1, child_2);
manager.saveParent(parent_A);
List<Child> children = manager.getChildren(parent_A); // contains 1 and 2
// set 3 and 4 to A
manager.setChildren(parent_A, child_3, child_4);
manager.saveParent(parent_A);
children = manager.getChildren(parent_A); // contains 1, 2, 3 and 4 :-(
I don't want to use oprhanRemoval on the childs, they should exist without parents.
What can I do? Do I forgot some cascades? Do I have to re-attach the parent in my save method or sth. like that?
Regards, jacquipre