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.
The difference between One-to-many , Many-to-one and Many-to-Many is: One-to-many vs Many-to-one is a matter of perspective. Unidirectional vs Bidirectional will not affect the mapping but will make difference on how you can access your data. In Many-to-one the many side will keep reference of the one side.
The big difference in terms of table structure between one-to-one and one-to-many is that in one-to-one it is possible (but not necessary) to have a bidirectional relationship, meaning table A can have a foreign key into table B, and table B can have a foreign key into the associated record in table A.
The <many-to-one> element will be used to define the rule to establish a one-to-one relationship between EMPLOYEE and ADDRESS entities, but column attribute will be set to unique constraint and rest of the mapping file will remain as it was in case of many-to-one association.
What is the real difference between one to many and many to one relationship? There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With