删除 Parent 将 Child 值设置为 NULL 不删除它们

Deleting Parent setting Child values to NULL not deleting them

我有一个 User 实体,它有一个角色列表。 当我删除 user 时,我希望子角色也被删除。 但是,外键只是设置为 null 而未删除。你能解释一下为什么会发生这种行为吗?我添加了 CascadeType.ALL,我认为这会删除子角色。

User.java

@SerializedName("userrole")
@Expose
@OneToMany(mappedBy = "user", fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> userRoles = new ArrayList<Role>();

Role.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long     id;

@NotNull
private RoleEnum role;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user")
private User     user;

Table 删除后

+----+------+------+
| id | role | user |
+----+------+------+
|  1 |    0 | NULL |
|  2 |    1 | NULL |
|  3 |    2 | NULL |
|  4 |    3 | NULL |
|  5 |    4 | NULL |
|  6 |    5 | NULL |
|  7 |    6 | NULL |
|  8 |    7 | NULL |
+----+------+------+

如有任何帮助,我们将不胜感激。

您可以使用 orphanRemoval 属性实现此目的。引用 JPA 2.0 规范中的相关部分。

Associations that are specified as OneToOne or OneToMany support use of the orphanRemoval option. The following behaviors apply when orphanRemoval is in effect:

If an entity that is the target of the relationship is removed from the relationship (by setting the relationship to null or removing the entity from the relationship collection), the remove operation will be applied to the entity being orphaned. The remove operation is applied at the time of the flush operation. The orphanRemoval functionality is intended for entities that are privately "owned" by their parent entity. Portable applications must otherwise not depend upon a specific order of removal, and must not reassign an entity that has been orphaned to another relationship or otherwise attempt to persist it. If the entity being orphaned is a detached, new, or removed entity, the semantics of orphanRemoval do not apply.

If the remove operation is applied to a managed source entity, the remove operation will be cascaded to the relationship target in accordance with the rules of section 3.2.3, (and hence it is not necessary to specify cascade=REMOVE for the relationship

所以你的 OneToMany 注释看起来像,

@OneToMany(mappedBy = "user", fetch=FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true)