小编典典

Hibernate ManyToOne与OneToOne

hibernate

我看不到“多对一”关系与“一对一”关系的架构有什么区别:

@Entity
public class Order {

    @ManyToOne
    @JoinColumn(nullable = false)
    private Address address;

@Entity
public class Order {

    @OneToOne
    @JoinColumn(nullable = false)
    private Address address;

有什么区别吗?


阅读 379

收藏
2020-06-20

共1个答案

小编典典

它们在架构上看起来完全相同,但是在Hibernate Layer上有所不同。

如果尝试这样的操作:

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

一切都会好起来的。但是,保存后,如果您尝试获取订单:

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

@ManyToOne case:
SUCCESS

当然,在两种情况下,您的Address类应该看起来有所不同。

2020-06-20