3

Can anyone provide me with a web-link which describes attribute-based simple one-to-many mapping very clearly?

For example (A company can have only one country of origin. But there are many Companies in a Country):

class Company
{
}

class Country
{
    IList<Company> Items;
}

1 Answer 1

4

For your example class, and using a bag for an unordered collection:

using Map = NHibernate.Mapping.Attributes;

[Map.Class( 0, Table = "country", NameType=typeof(Country) )]
public class Country
{
    [Map.Id( 1, Name = "Id" )]
    [Map.Generator( 2, Class = "identity" )]
    public virtual int Id { get; set; }
    [Map.Property]
    public virtual string Name { get; set; }
    [Map.Bag( 0, Table = "country_company" )]
    [Map.Key( 1, Column = "countryid" )]
    [Map.OneToMany( 2, ClassType = typeof( Company ) )]
    public virtual IList<Company> Items { get; set; } 
}

[Map.Class( 0, Table = "country_company", NameType = typeof( Company ) )]
public class Company
{
    [Map.Id( 1, Name = "Id" )]
    [Map.Generator( 2, Class = "identity" )]
    public virtual Guid Id { get; set; }
    [Map.Property]
    public virtual string Name { get; set; }
}

produces the following hbm.xml:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="nh.Country, nh" table="country">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="Name" />
        <bag name="Items" table="country_company">
            <key column="countryid" />
            <one-to-many class="nh.Company, nh" />
        </bag>
    </class>
    <class name="nh.Company, nh" table="country_company">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="Name" />
    </class>
</hibernate-mapping>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.