I have the following classes which I would like to map using NHibernate
class User
{
long Id {get; set;}
IList<UserPassword> OldPasswords {get; set}
}
class UserPassword
{
long UserId {get; set;}
string Password {get; set;}
DateTime CreateDtm {get; set;}
}
In the UserPassword table in the database (Oracle) UserId, Password and CreateDtm are a composite key (I cant change this)
At present my mapping files look like
<hibernate-mapping assembly="DomainEntities" namespace="DomainEntities.Models" xmlns="urn:nhibernate-mapping-2.2">
<class name="User" table="USERS" lazy="true" >
<id name="Id">
<column name="USER_ID" sql-type="NUMBER" not-null="true" unique="true"/>
<generator class="identity"/>
</id>
<bag name="OldPasswords" cascade="all" inverse="true">
<key column="USER_ID" not-null="true" />
<one-to-many class="UserPassword" />
</bag>
</class>
</hibernate-mapping>
<hibernate-mapping assembly="DomainEntities" namespace="DomainEntities.Models" xmlns="urn:nhibernate-mapping-2.2">
<class name="UserPassword" table="USER_PASSWORDS" lazy="true" >
<composite-id>
<key-property name="UserId" column="USER_ID" />
<key-property name="Password" column="OLD_PASSWORD" />
<key-property name="CreateDtm" column="CREATE_DATE" />
</composite-id>
</class>
</hibernate-mapping>
When querying for the user object, its loading the user passwords correctly, however, I cant add or remove a new password to the list.
I have tried adding in a mapping on the User object, but when trying to commit the transaction, its thrown an exception on an invalid array index for the CreateDtm. I suspect this is because of the composite key.
Am I missing something in my mapping, or is this a scenario that just cant be done?
I was missing the tag in the composite id.
The composite-id now looks like
The other part to this problem, was the cascade mode, on the parent. I needed to set cascade to “add-delete-orphan” to delete the items removed from the collection.