hey guys
hope this is the correct forum to post into?!
we're trying to get to the bottom of the following error message but are not able to find a solution, even with help from several search engines and other forums:
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
We're using spring (and thus also hibernate) and javax.persistence.
We have a bidirectional parent-child relationship between 2 classes, lets call'em +Parent+ and +Child+.
The following code is inside class
Parent:
Code:
public class Parent implements Serializable{
...
private Child childObject;
...
@ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
@JoinColumn(name = "child_object")
public Child getChildObject() {
return childObject;
}
public void setChildObject(Child childObject) {
if(childObject != null)
childObject.register(this);
this.childObject = childObject;
}
....
}
The Child-class looks similar to this:
Code:
public class Child implements Serializable{
private Set<Parent> parents;
...
@OneToMany(mappedBy="child_object", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<Parent> getParents() {
return parents;
}
public void setParents(Set<Parent> parents) {
this.parents= parents;
}
public void register(Parent parent) {
this.parents.add(parent);
}
..
}
So far, so good. Now, if we test (using TestNG and extending the test class with AbstractTransactionalTestNGSpringContextTests) this setup using the testcode below, the exception mentioned above is thrown:
Code:
public class ChildDAOTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private ChildDAO childDAO;
@Autowired
private ParentDAO parentDAO;
@Test
public void testRegister(){
Parent parent = TestHelper.createParent("TestParent");
Child child = new Child("ChildTest");
parent.setChildObject(child);
/* save(parent) invokes getJpaTemplate.merge(parent). The implementation JpaParentDAO of interface ParentDAO extends JpaDaoSupport. */
parent= parentDAO.save(parent);
Parent duplicatedParent = new Parent("duplicate");
duplicatedParent .setChildObject(parent.getChildObject());
/* the following line throws the exception */
duplicatedParent = parentDAO.save(duplicatedParent );
}
The problem lies inside setChildObject() of class Parent when executing register() on class Child. Although we know that the exception is caused there, we cannot figure out why and find a proper solution. It seems that there is a problem when adding a transient instance of Parent to a set of Parents inside Child, if Child has already been persisted.
Does anybody have insight on this exception or problem in general? Any help is greatly appreciated!
Cheers, Rox