Go NHibernate Tour (9): Explore parent-child relationships (one-to-many relationships)

Source: Internet
Author: User
Tags throw exception

The content of this section

    • Introduced
    • Collection types in NHibernate
    • Establish a parent-child relationship
    • Parent-Child Association mappings
    • Conclusion
Introduced

Through the introduction of the previous articles, basically understand the nhibernate, but in the nhibernate mapping relationship is the highlight of NHibernate, but also the most difficult to master technology. From this beginning to learn these things, I will combine graphics and texts to illustrate the knowledge of the mystery here.

For the first few, our example only uses a simple customer object. But in the classic combination of customer/order/product, their relationship is very complex. Let's review the data model established in the second article.

On the diagram, I have clearly labeled the relationships between the tables, first analyzing the "foreign key relationship" between the customer and order, or the "parent-child relationship", "one-to-many relationship." Get an initial look at the collections in NHibernate before analyzing them.

Collection types in NHibernate

NHibernate supports/defines several types of collections:

Bag: Object collection, each element can be duplicated. For example {1,2,2,6,0,0}, the equivalent of IList or ilist<t> implementations in. Net.

Set: Object collection, each element must be unique. For example {1,2,5,6}, equivalent to Iset or iset<t> implementations in. NET, Iesi.Collections.dll assemblies provide Iset collections.

List: Integer Index object collection, each element can be duplicated. For example {{1, "Yjinglee"},{2, "Cnblogs"},{3, "Liyongjing"}}, is equivalent to arrarylist or list<t> implementation in. NET.

Map: A collection of key-value pairs. For example {{"Yjinglee", 5},{"Cnblogs", 7},{"Liyongjing", 6}, in. NET is equivalent to Hashtable or idictionary<tkey,tvalue> implementation.

In fact, we use the Set collection type in most cases, because this type and relational database model are relatively close.

Establish a parent-child relationship

Look directly at the two tables of the following picture:

The two table relationships above mean that the customer has one or more orders,orders that belong to a customer. In general, we call the customer "parent" and order called "Child". The relationship between customer and order has several claims: "Foreign key Relationship", "parent-child relationship", "one-to-many relationship".

1.Customer has one or more orders

In the object model: orders is used as a collection in the customer class, so it can be said that the customer object contains the Orders collection. This is usually stated in. NET:

public class customer{    //...    Public ilist<order> orders{get; set;}}

Access to objects by: access by sub-collection: customer.orders[...]

In NHibernate, it is common to use the Iset collection in the Iesi.Collections.dll assembly, now to modify the Customer.cs class, you first need to reference the assembly, and the Customer.cs class code is as follows:

Using Iesi.collections.generic;namespace domainmodel.entities{public    class Customer    {public        virtual int CustomerId {get; set;}        Public virtual string Firstname {get; set;}        Public virtual string Lastname {get; set;}        One-to-many relationship: customer has a single or more orders public        virtual iset<order> orders {get; set;}}    }
2.Order belongs to a customer

In the object model: When customer is a single object in the Order class, you can say that the order object contains a customer. This is usually stated in. NET:

public class order{    //...    customer{get; set;}}

How it accesses objects: Access by members of the parent object: Order.customer

We create the Order.cs class in the Entities folder of the project Domainmodel layer and write the following code:

namespace domainmodel.entities{public    class Order    {public        virtual int OrderId {get; set;}        Public virtual DateTime OrderDate {get; set;}        Many-to-one relationship: orders belong to a customer public        virtual customer customer {get; set;}}    }

Well, now that we're done with the persistence class, here's a look at how these two classes map.

Parent-Child Association mappings

In NHibernate, we can correlate relationships between objects through a mapping file. The mapping file defines:

    • Relationship between objects: a pair of one or one-to-many, many-to-one, many-to-many relationships.
    • Controlling cascading behavior in relationships (Cascade behavior): Cascading updates, cascading deletions
    • Bidirectional navigation between father and son (bidirectional navigation)
1. Parent Entity Mappings

The parent entity (Customer) mapping defines:

    • Collection type (Bag, Set, List, Map)
    • cascading behavior when saving, updating, deleting operations
    • Control direction of the association:
      • Inverse= "false" (default): Parent entity is responsible for maintaining association relationships
      • Inverse= "true": child entities are responsible for maintaining association relationships
    • Relationships associated with child entities (one-to-many, many-to-a, many-to-many)

These specific settings are the nhibernate of the puzzle, and later slowly discuss the mysteries of these different settings.

This article initially establishes a one-to-many relationship between the customer and order, modifying the Customer.hbm.xml mapping file as follows:

<?xml version= "1.0" encoding= "Utf-8"? >set Name= "Orders" table= "Order" "generic=" true "inverse=" true "> <key column=" Customer "foreign-key=" FK _customerorders "/> <one-to-many class=" Domainmodel.entities.order,domainmodel "/> </set></class>

As you can see, the "parent" side mapping uses the set element, which indicates that the attribute name, table name, and child entity are responsible for maintaining the association relationship.

2. Child Entity Mappings

The child Entity (Order) mapping defines something that is less of a parent entity: (Many-to-many, many-to-many, one or one-to-more) relationships associated with the parent entity, and a pointer to the parent entity.

On the "child" side, the association with the "parent" side is defined by the Many-to-one element, which is a many-to-one association (actually a reference to the Customer object) from the "Child" side perspective. Here's a look at the Many-to-one element mapping properties:

See what these mapping attributes mean:

  • Access (default property): Optional field, property, Nosetter, classname value. NHibernate the policy that accesses the property.
  • Cascade (optional): Indicates which actions are cascaded from the parent object to the associated object. The all, save-update, delete, and none values are optional. Other than none, the specified action is extended to the associated (child) object.
  • Class (the default is to get the property type by reflection): The name of the associated class.
  • Column (default property name): The name of the columns.
  • Fetch (Default Select): Optional select and join values, select: Crawl associations with separate queries, join: Always fetch associations with outer joins.
  • Foreign-key: Foreign key name, using the name generated by the Schemaexport tool.
  • Index: ...
  • Update,insert (Default true): Specifies whether the corresponding field is included in the SQL statement used for UPDATE or insert. If both are false, this is a purely "exogenous (derived)" Association whose value is obtained by mapping to some other attribute of the same (or multiple) field, or by other programs through the trigger.
  • Lazy: Optional false and proxy values. Whether to delay, not delay, or use agent latency.
  • Name: Property name PropertyName.
  • Not-found: Optional ignore and exception values. Could not find the ignore or throw exception.
  • Not-null: Optional true and false values.
  • Outer-join: Optional Auto, True, False value.
  • Property-ref (optional): Specifies a property name for the associated class that corresponds to the foreign key. If not specified, the primary key of the other association class is used. This property is usually used in a legacy database system, and there may be a very bad relational model when a foreign key points to a non-primary key field (but should be a unique keyword) of the associated table. For example, suppose the customer class has a unique CustomerID, which is not a primary key. This has a full experience in the NHibernate source code.
  • Unique: Optional true and false values. Controls the process by which NHibernate generates DDL through the Schemaexport tool.
  • Unique-key (optional): Use DDL to generate a unique constraint for the foreign key field.

Let's create a "child" to the "parent" side of the map, create a new Order.hbm.xml file, write code as follows:

<?xml version= "1.0" encoding= "Utf-8"? >many-to-one name=" Customer "column=" Customer " Not-null= "true"                 class= "Domainmodel.entities.customer,domainmodel"                 />  </class>< /hibernate-mapping>

A glance at the properties on how to correlate them.

Go NHibernate Tour (9): Explore parent-child relationships (one-to-many relationships)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.