Mapping NHibernate many-to-many with a Class for the Joining Table
I wanted to have a many to many association in nhibernate so that additional info can be added to the joining table. Like the date the relationship was setup. I couldn’t quickly find anything on google, but then remembered that this is really 4 associations in nhibernate; one-to-many : many-to-one for ClassA and one-to-many : many-to-one for ClassB.
In this example we’re not going to map one-to-many from ClassB. ClassB will not know about this relationship, which will result in orphaned records if we delete any ClassB records.
Mapping for Class A:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" default-lazy="true" assembly="Core" namespace="Core.Models">
<class name="ClassA" table="classA">
<id name="Id">
<generator class="guid.comb"></generator>
</id>
<set name="Matches" cascade="all-delete-orphan" lazy="true" inverse="true">
<key column="ClassAId" />
<one-to-many class="ClassAMatch" />
</set>
</class>
</hibernate-mapping>
Above ClassAMatch is the many-to-many class. The set is the one-to-many association to ClassAMatch.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" default-lazy="true" assembly="Core" namespace="Core.Models">
<class name="ClassAMatch" table="ClassAMatches">
<id name="Id">
<generator class="guid.comb"></generator>
</id>
<many-to-one name="ClassA" column="ClassAId" lazy="false" cascade="none" not-null="true" />
<many-to-one name="ClassB" column="ClassBId" lazy="false" cascade="none" not-null="true" />
<property name="MatchedOn" not-null="true" update="false" />
</class>
</hibernate-mapping>
Above, this sets up the many-to-one associations to ClassA and to ClassB. This will be enough to persist the relation, but remember it will leave orphaned records if ClassB records are deleted since ClassB doesn’t know about his relationship/association. To fix that add a similar set mapping to that shown for ClassA.
Webmentions
These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: