JPA 中的聚合和分解

发布于 2024-10-06 04:43:17 字数 67 浏览 4 评论 0原文

如何使用 Java Persistence API 实现聚合和分解?最佳实践是什么?

提前致谢, 丹尼尔

How do you implement aggregation and decomposition with Java Persistence API? What are the best practices?

Thanks in advance,
Daniel

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隐诗 2024-10-13 04:43:17

我找到了 @OneToMany@OneToOne 关系的 orphanRemoval 属性:

当一对一或一对多关系中的目标实体从关系中删除时,通常需要将删除操作级联到目标实体。此类目标实体被视为“孤立实体”,并且 orphanRemoval 属性可用于指定应删除孤立实体。例如,如果订单有多个订单项,并且其中一个订单项已从订单中删除,则删除的订单项将被视为孤立订单项。如果 orphanRemoval 设置为 true,则当从订单中删除订单项时,该订单项实体将被删除。

用法:

@OneToMany(mappedBy="customer", orphanRemoval=true)
public List<Order> orders;

I've found the orphanRemoval attribute for @OneToMany and @OneToOne relationships:

When a target entity in one-to-one or one-to-many relationship is removed from the relationship, it is often desirable to cascade the remove operation to the target entity. Such target entities are considered “orphans,” and the orphanRemoval attribute can be used to specify that orphaned entities should be removed. For example, if an order has many line items, and one of the line items is removed from the order, the removed line item is considered an orphan. If orphanRemoval is set to true, the line item entity will be deleted when the line item is removed from the order.

Usage:

@OneToMany(mappedBy="customer", orphanRemoval=true)
public List<Order> orders;
揪着可爱 2024-10-13 04:43:17

在 JPA 中处理聚合时,有两件事应该非常清楚。

  1. 关系世界中的关系。
  2. 对象世界中所需的关系。

Java 世界中的关系是由领域需求决定的。例如,一个用户可能有很多地址,因此我们保留用户中地址的聚合,而不保留逆关系。对于组合,我们需要处理级联行为。

更详细的处理可以参见此处

There are two things which should be very clear while handling aggregation in JPA.

  1. The relationship in the relational world.
  2. The relationship required in the object world.

The relationship in Java world is governed by the domain need. For example a User might have many addresses so we keep the make the aggregation of address in User and not keep the inverse relationship. For composition, we need to handle the cascade behavior.

A more detail treatment can be see here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文