Playready test site. When I was integrating NHibernate into an existing enterprise software with a legacy database, it took me some time to figure out how mappings for composite keys with associations between entities should be set. This simplified example might be useful to start with for who's trying the same thing.
The article NHibernate and Composite Keys by Anne Epstein provides a thorough explanation on fundamental composite keys mapping and supporting lazy loading by declaring the composite keys as a class object. Here we only focus on a simple code sample of the associations between entities with composite keys.
The most common primary key mapping is available through Id method. There are several features missing - like unsaved-value (will be added in NHibernate 3.3) or DDL column options. Probably the most important option is Generator. It specifies the way NHibernate (or database) generates unique values. Hibernate generator element generates the primary key for new record. In this lesson you will learn about hibernate method in detail. In this lesson you will learn about hibernate generator method in detail.
Considering 2 sample tables, Products and Orders:
Products
Orders
StoreID
NUMBER
PK
ProductID
ProductName
VARCHAR
OrderID
Amount
There is no relationship between both tables in the database but apparently the association from Products to Orders is one-to-many.
ProductIdentifier
Product
In the Product entity class definition, we add a ISetcollection property of Order entity type. The collection property represents the Order class objects associated with the Product class object. We need to include the Iesi.Collectionlibrary which comes with the NHibernate package.
ISet
Order
Iesi.Collection
In the Product XML mapping file the ID of Product entity is mapped by <composite-id> element.
<composite-id>
Debian generate ssh key for user. The ISetcollection property defined previously is mapped by <set> element:
<set>
<key>
The mapping of Orders table is similar to what we just did above. Since it has a many-to-one association with Products, we add a Product class type property in the Order class definition.
In the corresponding mapping file, the <many-to-one> element specifies the association with Product entity and the <column> elements are the foreign keys of the Orders table referring to the Products table.
That鈥檚 all needed for the association to work. Adding a <version> element in the mapping is recommended for long transactions if adding a new version column of the table in the legacy database is allowed.
<version>