Hi,
I can't quite work out how to map my domain model using hibernate. I have two classes (let's call them Parent and Child). As usual, there are multiple Child objects per Parent (although this multiplicity is not represented on the Parent) and each Child has one Parent. Each Parent cares about at most one Child at a time (possibly no Children). The Child that the Parent cares about changes from time to time. In my domain model, I represent therefore only the many-to-one Child-Parent relationship and the one-to-one Parent-Child relationship:
class Parent {
private Child favouriteChild;
+ getter / setter
}
class Child {
private Parent parent;
+ getter / setter
}
In the db-schema, I have the following:
CREATE TABLE Parent (
parent_id int not null,
fav_child_id int
)
CREATE TABLE Child (
child_id int not null,
parent_id int not null
)
with PK and FK constraints where you'd expect them. I'm happy that the domain model and the db-schema represent the information I need; my problem is the Hibernate mappings.
Now, I'm hoping that I can create a Parent, set a Child as favouriteChild and then save the Parent and have the inserts cascaded to the Child table.
As there may be multiple Child objects per Parent, I can't follow the documentation's suggestion to map this unidirectional one-to-one on a foreign key as a many-to-one with unique="true" (as suggested in 7.2.2). Section 7.6 on "More complex association mappings" looks more like what I want, but I'm buggered if I can work out what SQL should go in the formula part of the definition of a derived property. Currently, I have the following mappings:
<hibernate-mapping>
<class name="Parent" table="Parent">
<id name="id" type="integer" name="parent_id">
<generator class="native"/>
</id>
<one-to-one name="favouriteChild" class="Child" cascade="all" property-ref="parent"/>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="Child" table="Child">
<id name="id" type="integer" name="child_id">
<generator class="native"/>
</id>
<many-to-one name="parent" class="Parent"
cascade="none" column="parent_id" not-null="true"/>
</class>
</hibernate-mapping>
I'm not sure that I want 'property-ref="parent"' on the favouriteChild mapping, but it's the closest thing to working I've found yet. I think the main problem is the circular reference; is there any way to get Hibernate to insert a Parent, insert a Child and then update the Parent.fav_child_id column with the id of the inserted Child, and do all of this with a single call to save()? Currently, the cascade works, so that both Parent and Child are saved, but the fav_child_id column is always left blank.
Thanks for any help.
Dean.
|