Hibernate - why use many-to-one to represent a one-to-one?

后端 未结 5 982
再見小時候
再見小時候 2020-11-28 06:40

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 cu

5条回答
  •  我在风中等你
    2020-11-28 07:14

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

提交回复
热议问题