Hibernate - 为什么使用多对一来表示一对一? [英] Hibernate - why use many-to-one to represent a one-to-one?
问题描述
我见过人们使用多对一的映射来表示一对一的关系。我还在Gavin King的一本书和文章中阅读了这些内容。
例如,如果客户可以只有一个送货地址,并且送货地址可以属于只给一个客户,映射如下: < class name =Customertable =CUSTOMERS>
...
<多对一名称=shippingAddress
class =地址
column =SHIPPING_ADDRESS_ID
cascade =save-更新
unique =true/>
...
< / class>
本书原因如下(引用它):
您不关心关联的目标端是什么,因此您可以像 to-one 关联那样对待它,而不用使用 / b>
我的问题是,为什么要使用多对一
而不是一对一
?什么是一对一
,这对于多对一
来说是不太理想的选择?
谢谢。
数据库中的一对一关联:您可以共享主键,但也可以使用具有唯一约束的外键关系(一个表具有引用关联表的主键的外键列)。
在后面的例子中,映射它的hibernate方法是使用多对一
关联它允许指定外键)。
lockquote
原因很简单:你不关心
目标端有什么的
协会,所以你可以把它看作
a to-one协会,而不需要很多
部分。所有你想要表达的是这个
实体有一个属性是
引用另一个
实体的实例,并且使用一个外键字段
表示
换句话说,使用多对一
是映射一对一外键关联(实际上可能比共享主键一对一关联更频繁)的方式。
I've seen people use many-to-one mappings to represent one-to-one relationships. I've also read this in a book by Gavin King and on articles.
For example, if a customer can have exactly one shipping address, and a shipping address can belong to only one customer, the mapping is given as:
<class name="Customer" table="CUSTOMERS">
...
<many-to-one name="shippingAddress"
class="Address"
column="SHIPPING_ADDRESS_ID"
cascade="save-update"
unique="true"/>
...
</class>
The book reasons as (quoting it):
"You don't care what's on the target side of the association, so you can treat it like a to-one association without the many part."
My question is, why use many-to-one
and not one-to-one
? What is it about a one-to-one
that makes it a less desirable option to many-to-one
?
Thanks.
There are several ways to implement a one-to-one association in a database: you can share a primary key but you can also use a foreign key relationship with a unique constraint (one table has a foreign key column that references the primary key of the associated table).
In the later case, the hibernate way to map this is to use a many-to-one
association (that allows to specify the foreign key).
The reason is simple: You don’t care what’s on the target side of the association, so you can treat it like a to-one association without the many part. All you want is to express "This entity has a property that is a reference to an instance of another entity" and use a foreign key field to represent that relationship.
In other words, using a many-to-one
is the way to map one-to-one foreign key associations (which are actually maybe more frequent than shared primary key one-to-one associations).
这篇关于Hibernate - 为什么使用多对一来表示一对一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!