简体   繁体   中英

Is it one-to-one or Component ? Nhibernate Mapping

Assume that I have Person and Address Classes and they have different tables in DB.

One Person can have one Address Class in it. This is the important part for me. One Person can have only one Address as it s child element and i want to keep them in different tables in DB.

Normally i know that i need to hold them in the same table, but my scenario needs this.

(and also it looks like a one-to-many but i dont want to have a collection just for one object)

Person     Address
-------    -------
id         id
Name       PersonId
           StreetName

And class code

Person                                                 
--------
public virtual long Id{get;set;}
public virtual Address MyAddress {get;set;}

As you see i want to get Address Property in Person when i get any Person ? But they are in different tables. How can this mapping be done ?

Thanks in advance

You can't map Address using a component because it has its own table. You could use it if you had all fields in just one table. From the Hibernate reference:

The component element maps properties of a child object to columns of the table of a parent class.

You should use a one-to-one relationship to map the tables and classes in you scenario.

要在数据库中强制执行一对一,您还可以对 Address 表中的 PersonId 设置唯一约束。

Are you sure it's a one to one relationship? I would assume it's a many-to-one relationship as usually more then one person can live at a certain address.

Anyways if it's a many-to-one relationship I'd map them like so. What I would do in your case is remove the PersonId FK from the Address table and put reference the Address Table from the Person table so you'd have something like this.

Person    Address
------    -------
id        id
Name      StreetName
AddressId

<many-to-one name="MyAddress" class="Address" column="AddressId"/>

and if you do insist on a one-to-one relationship I would recommend merging the two tables together.

I have used the code below in Person mapping to get it done.

<one-to-one lazy="proxy" name="MyAddress" class="Address" property-ref="PersonId" cascade="delete" />

Hope helps someone else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM