One of my favorite features in an ORM is the ability to represent associations as first class elements. But my parent/child implementations observed this weird behavior: after adding the child, NHibernate didn't issue one SQL INSERT command, but an INSERT that didn't set the foreign key, followed by an UPDATE that did set it.
After some googling I found the answer here: the underlying cause of this behaviour is that the link (the foreign key) from parent to child is not considered part of the state of the child object and is therefore not created in the INSERT. So the solution is to make the link part of the child mapping, something like this:
<many-to-one name="parent" column="parent_id" null="true">
</many-to-one>
Now that the child entity is managing the state of the link, we tell the collection not to update the link. We use the inverse attribute:
<set name="children" inverse="true">
<key column="parent_id">
<one-to-many class="Child">
</one-to-many>
</key>
</set>
No comments:
Post a Comment