Thx for the reply, panisson. My Person/Address example is somewhat different from yours
If the Child class has its on ID column based on DB sequence, Hibernate has no problem in creating the object graph in one go using regular bidrectional one-to-many mapping.
But my legacy DB's Child class has a composite key:
Code:
CREATE TABLE Child (
parentId INTEGER NOT NULL,
childNumber INTEGER NOT NULL
);
ALTER TABLE Child
ADD ( PRIMARY KEY (parentId, childNumber) ) ;
CREATE TABLE Parent (
parentId INTEGER NOT NULL
);
ALTER TABLE Parent
ADD ( PRIMARY KEY (parentId) ) ;
and my mapping is:
Code:
<class name="Parent" table="PARENT">
<id name="parentid" type="long">
<generator class="sequence">
<param name="sequence">seq_parentId</param>
</generator>
</id>
<set name="childs" inverse="true" cascade="all-delete-orphan">
<key column="PARENTID" not-null="true" />
<one-to-many class="Child" />
</set>
</class>
<class name="Child" table="CHILD">
<composite-id name="id" class="ChildId">
<key-property name="parentid" type="long" />
<key-property name="childnumber" type="long" />
</composite-id>
<many-to-one name="parent" class="Parent" update="false" insert="false" fetch="select" />
</class>
But when I run the following code:
Code:
// Pres tier construct obj graph
Parent p = new Parent();
Child c = new Child();
c.setParent(p);
ChildId cid = new ChildId(); // needs parentId and childNumber
cid.setChildnumber(101);
//don't know what to put for ChildId.parentId, so it's NULL
c.setId(cid);
p.getChilds().add(c);
// DAO tier
Session ssn = sessionFactory.openSession();
Transaction tx = ssn.beginTransaction();
Serializable s;
s = ssn.save(p);
tx.commit();
ssn.close();
I got exception on NULL ChildId.parentId:
Code:
Hibernate: /* insert Parent */ insert into SCOTT.PARENT (PARENTID) values (?)
Hibernate: /* insert Child */ insert into SCOTT.CHILD (PARENTID, CHILDNUMBER) values (?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
...
Caused by: java.sql.BatchUpdateException: ORA-02291: integrity constraint (SCOTT.SYS_C002917) violated - parent key not found
How can Hibernate handle this common use case gracefully?