且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPA:单向多对一和级联删除

更新时间:2022-01-31 10:00:18

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操作,以便 EntityManager.remove 将删除父级和子级。您还可以指定 orphanRemoval 如果为true,则在父集合中的子实体设置为null时删除任何孤立子节点,即在子节点不存在于任何父集合中时删除子节点。

  • 或者,将子表中的外键约束指定为 ON DELETE CASCADE 。您需要调用 EntityManager.clear() 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 that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval 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 invoke EntityManager.clear() after calling EntityManager.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.