简体   繁体   English

是一对一还是 Component ? 休眠映射

[英]Is it one-to-one or Component ? Nhibernate Mapping

Assume that I have Person and Address Classes and they have different tables in DB.假设我有 Person 和 Address 类,并且它们在 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 ?如您所见,当我得到任何 Person 时,我想亲自获得 Address 属性? 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.在你的情况下,我会做的是从地址表中删除 PersonId FK 并从人员表中引用地址表,这样你就会有这样的东西。

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.我在 Person 映射中使用了下面的代码来完成它。

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

Hope helps someone else希望能帮助别人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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