问题描述
说我有单向 @ManyToOne
之类的关系,如下所示:
Say I have a unidirectional @ManyToOne
relationship like the following:
@Entity
public class Parent implements Serializable {
@Id
@GeneratedValue
private long id;
}
@Entity
public class Child implements Serializable {
@Id
@GeneratedValue
private long id;
@ManyToOne
@JoinColumn
private Parent parent;
}
如果我有父P和子C 引用回P,在JPA中有一个干净漂亮的方法来自动删除子C ... C 当P被删除时(即 entityManager.remove(P)
)?
If I have a parent P and children C...C referencing back to P, is there a clean and pretty way in JPA to automatically remove the children C...C when P is removed (i.e. entityManager.remove(P)
)?
我正在寻找的功能类似于SQL中的 ON DELETE CASCADE
。
What I'm looking for is a functionality similar to ON DELETE CASCADE
in SQL.
推荐答案
JPA中的关系始终是单向的,除非您在两个方向上将父级与子级关联。从父母到孩子的级联REMOVE操作将需要从父母到孩子的关系(而不仅仅是相反的)。
Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).
因此,您需要这样做:
You'll therefore need to do this:
- 或者,将单向
@ManyToOne
关系更改为双向@ManyToOne
,或单向@OneToMany
。然后,您可以级联REMOVE操作,以便将删除父级和子级。您还可以指定如果为true,则在父集合中的子实体设置为null时删除任何孤立子节点,即在子节点不存在于任何父集合中时删除子节点。 - 或者,将子表中的外键约束指定为
ON DELETE CASCADE
。您需要调用 EntityManager.html #remove%28java.lang.Object%29rel =noreferrer>EntityManager.remove(parent)
,因为持久性上下文需要是刷新 - 在数据库中删除后,子实体不应存在于持久化上下文中。
- Either, change the unidirectional
@ManyToOne
relationship to a bi-directional@ManyToOne
, or a unidirectional@OneToMany
. You can then cascade REMOVE operations so thatEntityManager.remove
will remove the parent and the children. You can also specifyorphanRemoval
as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection. - Or, specify the foreign key constraint in the child table as
ON DELETE CASCADE
. You'll need to invokeEntityManager.clear()
after callingEntityManager.remove(parent)
as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.
这篇关于JPA:单向多对一和级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!