Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

orm - Hibernate - why use many-to-one to represent a one-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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...