Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nhibernate many-to-many mapping - additional column in the mapping table?

I have following mapping definitions:

  <class name="Role" table="Role" optimistic-lock="version" >

    <id name="Id" type="Int32" unsaved-value="0" >
      <generator class="native" />
    </id>

    <property name="RoleName" type="String(40)" not-null="true" />

    <bag name="UsersInRole" generic="true" lazy="true" cascade="all" table="UserRoles" >
      <key  column="RoleId" />
      <many-to-many column="UserId" class="SystemUser, Domain"/>
    </bag>

and

<id name="Id" type="Int32" unsaved-value="0" >
  <generator class="native" />
</id>
<property name="UserName" type="String(40)" not-null="true" unique="true" />

This mapping generates mapping table UserRoles, which has two columns - RoleId and UserId.

However, I'd like to add extra attributes to that relation - i.e. some enum values defining state of the relation as well as effective start & end dates.

Is it possible to do in nhibernate or do I need to add additional class here and change relation m-to-m into 2 relations [user] 1-to-m [user_role] m-to-1 [role] ?

like image 855
Greg Avatar asked May 20 '09 18:05

Greg


1 Answers

You need to add an extra class, e.g. UserRole, in code to keep the additional properties.

When it comes to mapping this can be mapped as a class as you mentioned. But I also think it can be mapped as a composite-element in the Role mapping:

<set name="UsersInRole" lazy="true" table="UserRoles" >
  <key  column="RoleId" />
  <composite-element class="UserRole">
     <many-to-one name="User" column="UserId" not-null="true"/>
     <propery name="RelationState" not-null="true"/>
     <propery name="StartDate" not-null="true"/>
     <propery name="EndDate" not-null="true"/>
  </composite-element>
</set>

All properties must be not-null, because they're become part of the primary keys of the UserRoles table. For more information see:

  • Nhibernate Composite Element Mapping
  • 7.2. Collections of dependent objects
like image 114
BengtBe Avatar answered Nov 19 '22 07:11

BengtBe