NHibernate provides several ways for collection mappings:
• | Set |
• | Bag |
• | List |
• | Map (Dictionary) |
• | Array |
Within the database, a one-to-many mapping is arranged as a table with a primary key for the one side of the mapping and another table that contains a field, which references the primary key of the first table.
There can be a collection of items with no key that would allow retrieving them from the collection. In the collection, all elements can be defined as unique (a Set) or, alternatively, they can be duplicated (a Bag).
It is also possible to arrange a collection of items with a key that allows retrieving those items from the collection. This key can be either an integer (a List) or another simple type, or even an object (in this case, it is called a Dictionary).
Set and Map Types of Collection Mapping Sample
The database contains the Dept and Emp tables, which have a foreign key constraint between them. The field DEPTNO in the table Emp receives the ID value of the associated record in the Dept table.
We perform the following sequence of operations:
As a result, we have the following model:
The association between the Dept and the Emp entities looks as follows:
|
In this example, we shall use the tables from the previous example for Set and Bag collection mapping. The model is created in the same way as in the previous example. After the model has been created, we need to display the Association Editor dialog. Through this dialog box, we need to set the Generate related property check box of the Dept navigation property to False, since only Set or Bag may be used for the “many” end of a bidirectional association. After that, we need to set the Collection type of the Emps navigation property to Map and specify the ENAME column as the Index column:
Now the Emps navigation property of the Dept class is mapped as Map collection mapping and is filled with instances of the Emp class. You can find the instances by looking in the mapped table for Emp and find records with the DEPTNO field having the value equal to DEPTNO field value of the Dept table. The ENAME field in the Emp table receives the key value of the entry in the dictionary. The key used in the map is of type String and can be found in the ENAME column of the table used to store the Emp objects. The type of the key used in this sample is string. |
List and Array types of collection mapping sample
The database contains the Message and Conversation tables, linked though the foreign key constraint. The ConversationId field in the Message table receives the id value of the associated record in the Conversation table. Additionally, the Message table has the Order column, the value of which determines the sequence of the message in the message list of each conversation.
We perform the following sequence of operations:
The association between the Message and the Conversation entities looks as follows:
As a result, we have the following model:
|