我有一个 User
实体,其中包含角色列表。
当我删除用户
时,我希望子角色也被删除。
然而,外键只是设置为空,并没有被删除。您能解释一下为什么会出现这种行为吗?我添加了 CascadeType.ALL
,我认为它会删除子角色。
User.java
@SerializedName("userrole")
@Expose
@OneToMany(mappedBy = "user", fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> userRoles = new ArrayList<Role>();
角色.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private RoleEnum role;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user")
private User user;
删除后的表格
+----+------+------+
| 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)
关于java - 删除父项将子值设置为 NULL 而不删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36049250/