NHibernate Pitfalls: Many to Many and Inverse

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

When you have a many to many relation in NHibernate, you can only set inverse to false on one side of the relation, not on both:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <hibernate-mapping default-lazy="false" namespace="SomeNamespace" assembly="SomeAssembly" xmlns="urn:nhibernate-mapping-2.2">
   3:     <class name="User" lazy="false" table="`USER`">
   4:         <id name="UsrId" access="property" column="`USR_ID`">
   5:             <generator class="hilo" />
   6:         </id>
   7:         <set cascade="all-delete-orphan" inverse="true" lazy="true" name="Notifications" table="`NOT_USR`">
   8:             <key column="`USR_ID`" />
   9:             <many-to-many class="Notification" column="`NOT_ID`" />
  10:         </set>
  11:     </class>
  12: </hibernate-mapping>

And:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <hibernate-mapping default-lazy="false" namespace="SomeNamespace" assembly="SomeAssembly" xmlns="urn:nhibernate-mapping-2.2">
   3:     <class name="Notification" lazy="false" table="`NOTIFICATION`">
   4:         <id name="NotificationId" access="property" column="`NOT_ID`">
   5:             <generator class="hilo" />
   6:         </id>
   7:         <property name="Comment" column="`COMMENT`" type="String" length="50"/>
   8:         <set cascade="all-delete-orphan" lazy="true" name="Users" table="`NOT_USR`">
   9:             <key column="`NOT_ID`" />
  10:             <many-to-many class="User" column="`USR_ID`" />
  11:         </set>
  12:     </class>
  13: </hibernate-mapping>

If you don’t, you won’t be able to save any associations.

Bookmark and Share

                             

No Comments