在双向JPA OneToMany / ManyToOne关联中,“关联的反面”是什么意思?

在《TopLink JPA注释参考》中的这些示例中:


示例1-59 @OneToMany-具有泛型的客户类


@Entity

public class Customer implements Serializable {

    ...

    @OneToMany(cascade=ALL, mappedBy="customer")

    public Set<Order> getOrders() { 

        return orders; 

    }

    ...

}

示例1-60 @ManyToOne-具有泛型的Order类


@Entity

public class Order implements Serializable {

    ...

    @ManyToOne

    @JoinColumn(name="CUST_ID", nullable=false)

    public Customer getCustomer() { 

        return customer; 

    }

    ...

}

在我看来,Customer实体是协会的所有者。但是,在mappedBy同一文档中对属性的说明中写道:


如果关系是双向的,则将关联的反(非所有权)侧的maptedBy元素设置为拥有该关系的字段或属性的名称,如示例1-60所示。


但是,如果我没有记错,则在示例中看起来,mappedBy实际上是在关联的拥有方而不是非拥有方指定了。


所以我的问题基本上是:


在双向(一对多/多对一)关联中,所有者是哪个实体?我们如何指定一方为所有者?我们如何指定多方为所有者?


“关联的反面”是什么意思?我们如何将一侧指定为逆?我们如何将“多面”指定为反面?


慕标琳琳
浏览 402回答 3
3回答

慕田峪7331174

令人难以置信的是,在过去的三年中,没有人用两种方式来描述您的关系来回答您的出色问题。正如其他人所提到的,“所有者”端在数据库中包含指针(外键)。您可以将任一侧指定为所有者,但是,如果将一侧指定为所有者,则关系将不会是双向的(反向(也称为“许多”侧)将不知道其“所有者”)。这对于封装/松散耦合可能是理想的:// "One" Customer owns the associated orders by storing them in a customer_orders join tablepublic class Customer {&nbsp; &nbsp; @OneToMany(cascade = CascadeType.ALL)&nbsp; &nbsp; private List<Order> orders;}// if the Customer owns the orders using the customer_orders table,// Order has no knowledge of its Customerpublic class Order {&nbsp; &nbsp; // @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally}唯一的双向映射解决方案是让“许多”一侧拥有其指向“一个”的指针,并使用@OneToMany“ mappedBy”属性。如果没有“ mappedBy”属性,Hibernate将期望进行双重映射(数据库将同时具有连接列和连接表,这是多余的(通常是不希望的))。// "One" Customer as the inverse side of the relationshippublic class Customer {&nbsp; &nbsp; @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")&nbsp; &nbsp; private List<Order> orders;}// "many" orders each own their pointer to a Customerpublic class Order {&nbsp; &nbsp; @ManyToOne&nbsp; &nbsp; private Customer customer;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java