小编典典

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

all

@OneToManyJPA
注释参考
的示例部分:

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

@Entity
public class Customer implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { 
        return orders; 
    }
    ...
}

示例 1-60 @ManyToOne - 带有泛型的订单类

@Entity
public class Order implements Serializable {
    ...
    @ManyToOne
    @JoinColumn(name="CUST_ID", nullable=false)
    public Customer getCustomer() { 
        return customer; 
    }
    ...
}

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

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

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

所以我的问题基本上是:

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

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


阅读 91

收藏
2022-09-02

共1个答案

小编典典

要理解这一点,你必须退后一步。在 OO 中,客户拥有订单(订单是客户对象中的列表)。没有客户就不可能有订单。因此,客户似乎是订单的所有者。

但在 SQL 世界中,一项实际上包含指向另一项的指针。由于 N 个订单有 1
个客户,因此每个订单都包含一个指向其所属客户的外键。这是“连接”,这意味着订单“拥有”(或字面上包含)连接(信息)。这与 OO/模型世界完全相反。

这可能有助于理解:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

反面是对象的OO“所有者”,在这种情况下是客户。客户在表中没有用于存储订单的列,因此您必须告诉它可以在订单表中的哪个位置保存此数据(通过
发生mappedBy)。

另一个常见的例子是树的节点既可以是父母也可以是孩子。在这种情况下,这两个字段在一个类中使用:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

这就解释了“外键”多对一的设计作品。还有第二种方法,它使用另一个表来维护关系。这意味着,对于我们的第一个示例,您有三个表:一个包含客户,一个包含订单,以及一个包含一对主键(customerPK、orderPK)的两列表。

这种方式比上面的方式更加灵活(可以轻松处理一对一、多对一、一对多甚至多对多)。价格是这样

  • 它有点慢(必须维护另一个表并且连接使用三个表而不是两个),
  • 连接语法更复杂(如果您必须手动编写许多查询,例如当您尝试调试某些东西时,这可能会很乏味)
  • 它更容易出错,因为当管理连接表的代码出现问题时,您可能会突然得到太多或太少的结果。

这就是为什么我很少推荐这种方法。

2022-09-02