Hibernate ManyToOne vs OneToOne

DD. picture DD. · Aug 27, 2013 · Viewed 16.2k times · Source

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?

Answer

paulek picture paulek · Aug 27, 2013

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.