java - 删除父项将子值设置为 NULL 而不删除它们

标签 java hibernate jpa one-to-many many-to-one

我有一个 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/

相关文章:

Java表达式编译错误

java - 为什么有一个元素没有显示?

mysql - hibernate中的重复记录

java - 如何以编程方式获取 Hibernate 模型的 jOOQ 表?

java - Hibernate 在双向映射中不生成键

java - 使用 Jersey Client 将输出流获取到请求主体?

java - 使用 JPA/hibernate 时是否可以将 orm.xml 定义与注释混合在一起?

java - 如何在单元测试期间注入(inject) PersistenceContext?

java - USE JpaWhere 带有列表 := Key

java - JPA:防止单向一对多映射中的级联更新