How To: NHibernate Parent/Child Relationships

So you’re trying to setup a Parent/Child relationship using NHibernate. This is easy enough when you allow the foreign keys to be null in your database. Of course this is not desirable for data integrity so you disallow nulls. Now NHibernate is pissed because it wants to insert the child row first then update it with the parent id.

You can fix this by setting up a bi-directional relationship. Simply put, try the following.

In your Parent.hbm.xml add:

<set name="Children" inverse="true" cascade="all-delete-orphan">
 <key column="parent_id"/>
 <one-to-many class="Child"/>

In your Child.hbm.xml add:

<many-to-one name="Parent" column="parent_id" not-null="true"/>

Now you need to make sure you update the Child class to “know about” the Parent. To make this easy add this method to your Parent class:

public void AddChild(Child c)
 c.Parent = this;

Now we can do this:

Parent p = new Parent();
Child c = new Child();

That’s the tall and skinny of it. To really understand this concept check out Chapter 16 of the NHibernate Reference Documentation.

2 thoughts on “How To: NHibernate Parent/Child Relationships

  1. a related question. we have a parent/child relationship set up between class A and class B.
    class B has a back-pointer to it’s parent – parentA. the mapping for the property in Class B looks like this (sorry for the formatting)…

    As can see, cascade is set to “none”. So i assumed that when we saved an instance of the child class B nothing would happen to the parent object A. Ah, but it turns out that if you update the instance of class A which is hanging off of class B and the update class B the change to A is persisted to the database and the version number on class A is incremented. Sort of exactly the same behaviour i would have expected if cascase=”true”. Any thoughts on why this is happening, anyone?
    Garth Engdahl

  2. hmm. my example of the mapping appears to have been eaten in the previous post. here it is again…

    <!– Many-to-One Foreign Key Association: Organization –>
    <!– Save Foreign Key reference, but don’t cascade update/deletes –>

Leave a Reply

Your email address will not be published. Required fields are marked *