Hi all,
I have a simple parent-child relationship:
The parent class:
Code:
@Entity
public class Parent implements Serializable {
@Id
@GeneratedValue
@Column(name = "PARENT_ID")
public long getId() {
return id;
}
// some other fields
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name = "PARENT_CHILD",
joinColumns = { @JoinColumn(name = "PARENT_ID") },
inverseJoinColumns = { @JoinColumn(name = "CHILD_ID") })
public Set<Child> getRelatedChildren() {
return relatedChildren;
}
}
...and the child class:
Code:
@Entity
public class Child implements Serializable {
private static final long serialVersionUID = -46484016106062423L;
private long id;
/**
* @return the id
*/
@Id
@GeneratedValue
@Column(name = "CHILD_ID")
public long getId() {
return id;
}
// some other fields
}
Now I get a Parent object from the DB, give it to the real world and get it back with some added children. Then I give this to my DAO for updating the existing one:
Code:
public void update(Parent parent) {
Parent parentFromDB = getParentById(parent.getId());
Set<Child> relatedChildrenFromDB = parentFromDB.getRelatedChildren();
// merge the new picture from incoming parent into the entity
relatedChildrenFromDB.addAll(parent.getRelatedChildren());
parentFromDB = (Parent)getCurrentSession.merge(parentFromDB);
}
Now, the new child is persisted, but all previous entries for this relation are thrown away. What is the trick to get it all together???
TIA,
Ralf