Hi All,
I'm attempting to use a bi-directional relationship (one-to-many) parent to child, whereby when I save (saveOrUpdate) the parent, the children are also CRUDed (inserted/updated/deleted). I'm pretty sure I've set it up correctly, however when I add an element to the children set, no new records appear in the database.
Parent:Code:
<hibernate-mapping>
<class name="package.ParentObject" table="parent_object">
<id name="id">
<generator class="sequence">
<param name="sequence">seq_parent_object_id</param>
</generator>
</id>
<set name="children" inverse="true" lazy="false" order-by="id">
<key column="ParentObjectId" not-null="true"/>
<one-to-many class="package.ChildObject"/>
</set>
<property name="childCount"/>
</class>
</hibernate-mapping>
Child:Code:
<hibernate-mapping>
<class name="package.ChildObject" table="child_object">
<id name="id">
<generator class="sequence">
<param name="sequence">seq_child_object_id</param>
</generator>
</id>
<many-to-one name="ParentObject" class="package.ParentObject" column="parentObjectId" lazy="false"/>
<property name="name"/>
</class>
</hibernate-mapping>
Usage:Code:
Session s = sessionFactory.getCurrentSession();
Transaction t = s.beginTransaction();
ParentObject parent = (ParentObject) s.get(ParentObject.class, new Long(1));
if (parent.getChildren().isEmpty())
{
ChildObject child = new ChildObject();
child.setParentObject(parent);
child.setName("test");
parent.getChildren().add(child);
}
parent.setChildCount(parent.getChildren().size());
s.saveOrUpdate(parent);
t.commit();
after this operation,
SELECT * FROM child_object WHERE parentObjectId=1 returns 0 records, while
SELECT childCount FROM parent_object WHERE id=1 returns 1, meaning the parent was updated but the new child was not inserted.
Is there anything obviously wrong with what I'm doing?NOTE: I have removed what I consider unrelated code/fields which
may be causing the problem, however if they are the cause then hibernate needs some better error reporting.