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