Using:
spring-2.0.6
hibernate-3.2.4.sp1
hibernate-annotations-3.3.0.ga
hibernate-commons-annotations-3.3.0.ga
hibernate-entitymanager-3.3.1.ga
hibernate-validator-3.0.0.ga
Issue:
I am using spring/jpa/hibernate for persistence and I am having issues with a very simple scenario. I have two domain objects. Let's call them Parent and Child:
Code:
@Entity
public class Parent
{
private Long id;
private List<Child> children;
public Parent()
{
children = new ArrayList<Child>();
}
@Id
@GeneratedValue
public Long getId()
{
return this.id;
}
private void setId(Long id)
{
this.id = id;
}
@OneToMany(mappedBy = "parent", cascade = {CascadeType.ALL})
public List<Child> getChildren()
{
return children;
}
public void setChildren(List<Child> children)
{
this.children = children;
}
}
@Entity
public class Child
{
private Long id;
private Parent parent;
@Id
@GeneratedValue
public Long getId()
{
return this.id;
}
private void setId(Long id)
{
this.id = id;
}
@ManyToOne
public Parent getParent()
{
return parent;
}
public void setParent(Parent parent)
{
this.parent = parent;
}
}
I have a service method wrapped in a transaction in which I get a parent and add a child to it:
Code:
Parent parent = parentDAO.get(id) // calls entityManager.find(Parent.class, id);
Child child = new Child();
child.setParent(parent);
parent.getChildren().add(child);
parentDAO.save(parent) // calls entityManager.merge(parent)
Right after calling save, the parent has two copies of the same child that I added. This causes two children to be inserted to the database (each with their own id). If I don't call save, it appears to work ok, but in real world usage, the parent that I get from the application may be detached.
Does anyone out there have any knowledge about why this would be happening and how I can fix the problem?
Thanks!
Will