Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate ManyToOne vs OneToOne

I can't see any difference in the schema of a Many-To-One relationship vs a OneToOne relationship:

@Entity public class Order {      @ManyToOne     @JoinColumn(nullable = false)     private Address address; 

vs

@Entity public class Order {      @OneToOne     @JoinColumn(nullable = false)     private Address address; 

Is there any difference?

like image 832
DD. Avatar asked Aug 27 '13 08:08

DD.


People also ask

What is difference between JPA unidirectional OneToOne and ManyToOne?

According to book Pro JPA 2 the main difference between unidirectional @ManyToOne and @OneToOne is that in @OneToOne: Only one instance of the source entity can refer to the same target entity instance. In other words, the target entity instance is not shared among the source entity instances.

What is Many-to-One relationship in Hibernate?

A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple employee objects.

What is the difference between many-to-one and one to many?

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.


2 Answers

They look exactly the same on schema but there is difference on Hibernate Layer.

If you try something like that:

Address address = new Address(); Order order1 = new Order(); order1.setAddress(address); Order order2 = new Order(); order2.setAddress(address); save(); 

Everything will be OK. But, after save if you try get Order:

@OneToOne case: org.hibernate.HibernateException: More than one row with the given identifier was found: 1  @ManyToOne case: SUCCESS 

Of course, your Address class should looks different in both cases.

like image 146
paulek Avatar answered Sep 27 '22 17:09

paulek


There should normally be a unique constraint on the address_id join column in the case of a OneToOne association, to guarantee that only one Order can have a given address.

like image 39
JB Nizet Avatar answered Sep 27 '22 18:09

JB Nizet