Hibernate version:
3.0.5
Given a simple Parent/Child relationship (like the one in chapter 22 of the manual), is it possible to set up such a mapping that would allow to create both parent and child before saving both of them at the same time?
In other words a mapping that would allow for this code:
Code:
Parent p = new Parent();
Child c = new Child();
p.getChildren().add(c);
c.setParent(p);
session.merge(p);
Logically, I would think that the mappings in section 22.3 of the manual should work. But instead I get "not-null property references a null or transient value" exception.
(From doing some instrumenting, it appears that Hibernate calls 'c.setParent(null) when it tries to do the 'session.merge()'... Why? Does it think that since Parent is transient (still), it should set the child's parent reference to null to prevent writing garbage to the DB? Why doesn't it first save Parent, get generated ID value and the save Child?..)
This code can clearly be made to work by having two calles to 'merge':
Code:
Parent p = new Parent();
session.merge(p);
Child c = new Child();
p.setChildren().add(c);
c.setParent(p);
session.merge(p);
The "problem" with this approach (in my case) is that Parent cannot logically exist w/o its children, and new children cannot be added arbitrarily - so I wanted to make constructor for Child package scoped (while still separating "model" code from "hibernate" code in separate packages).
Any solutions?