Hibernate——为什么用多对一来表示一对一? [英] Hibernate - why use many-to-one to represent a one-to-one?
问题描述
我见过人们使用多对一映射来表示一对一关系.我还在 Gavin King 的一本书和文章中读到了这一点.
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):
您不关心关联的目标端是什么,因此您可以将其视为 对一 关联而无需 many 部分."
"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."
我的问题是,为什么使用 many-to-one
而不是 one-to-one
?一对一
是什么使它成为多对一
的不太理想的选择?
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
?
谢谢.
推荐答案
在数据库中实现一对一关联的方法有多种:可以共享主键,也可以使用外键关系唯一约束(一个表具有引用关联表主键的外键列).
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).
在后一种情况下,hibernate 映射它的方法是使用 多对一
关联(允许指定外键).
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屋!