Hibernate ManyToOne vs OneToOne

前端 未结 4 2042
长发绾君心
长发绾君心 2020-12-08 00:40

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

@Entity
public class Order {

    @ManyToOne
    @JoinCol         


        
4条回答
  •  一个人的身影
    2020-12-08 01:21

    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.

提交回复
热议问题