Hibernate : Is Many-to-One is same as One-To-One mapping

In both these relation ship the source object has one foreign key or pointer to the target object.

For example : –
A car can have one owner – here the source object car will have pointer to target object person.

Many cars can have one owner – here too the source object car will have pointer to target object person.

In java or object world all the relationships are established from source object, target may or may not point to the source at all. However in RDBMS when a query is fired in relationship the inverse query or bi-directional relationship has to be there without violation.

A ManyToOne relationship in Java is where the source object has an attribute that references another target object and (if) that target object had the inverse relationship back to the source object it would be a OneToMany relationship. All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object. This is different than a relational database, in which relationships are defined through foreign keys and querying such that the inverse query always exists.

JPA also defines a OneToOne relationship, which is similar to a ManyToOne relationship except that the inverse relationship (if it were defined) is a OneToOne relationship. The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object’s table to the target object’s table, where as a OneToOne relationship the foreign key may either be in the source object’s table or the target object’s table.

In JPA a ManyToOne relationship is defined through the @ManyToOne annotation or the <many-to-one> element.

In JPA a ManyToOne relationship is always (well almost always) required to define a OneToMany relationship, the ManyToOne always defines the foreign key (JoinColumn) and the OneToMany must use a mappedBy to define its inverse ManyToOne.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.