Hibernate version:
Hibernate 3.1 beta 3
I have a problem with a bidirectional one-to-many relationship. The Parent contains a Collection of Children. If I add a Child to the Collection and merge the Parent the new Child ist stored in the database.
But when I clear the Collection and merge the Parent, the Child won't be deleted.
And when I change an attribute of the Child and merge the Parent, the existing Child isn't changed. The existing Child is left unchanged and a new Child is created instead.
Has anyone an idea how to delete or change a Child in a bidirectional one-to-many relationship?
Code:
@Entity
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
private long parentId;
private String description;
private Collection<Child> children = new HashSet<Child>();
public Parent() {
}
@Id(generate = GeneratorType.AUTO)
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
@Column(nullable=false,length=50)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@OneToMany(mappedBy="parent", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Collection<Child> getChild() {
return children;
}
public void setChild(Collection<Child> children) {
this.children = children;
}
}
@Entity
public class Child implements Serializable {
private static final long serialVersionUID = 5961273964796186950L;
private long childId;
private Parent parent;
private String description;
@Id(generate = GeneratorType.AUTO)
public long getChildId() {
return childId;
}
public void setChildId(long childId) {
this.childId = childId;
}
@ManyToOne (cascade=CascadeType.ALL)
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
@Column(nullable=false,length=50)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@Stateless
@Remote(ParentManager.class)
public class ParentManagerBean implements ParentManager, Serializable {
private static final long serialVersionUID = -2626162415851817422L;
@PersistenceContext
private EntityManager em;
public Parent addParent(String description) {
Parent parent = new Parent();
parent.setDescription(description);
em.persist(parent);
return parent;
}
public void updateParent(Parent parent) {
em.merge(parent);
}
}