[英]Hibernate soft delete sets foreign key to null
I have 2 entities like this:我有 2 个这样的实体:
@SQLDelete(sql = "UPDATE parent_table SET deleted = true WHERE id = ?")
public class Parent {
private boolean deleted;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id")
private List<Child> children;
// other stuff
}
@SQLDelete(sql = "UPDATE child_table SET deleted = true WHERE id = ?")
public class Child {
private boolean deleted;
// stuff
}
As you can see, its a unidirectional @OneToMany mapping and both entities use soft delete with the @SQLDelete
annotation.如您所见,它是一个单向的 @OneToMany 映射,并且两个实体都使用带有
@SQLDelete
注释的软删除。 I'm trying to soft delete the parent and in turn want the child to be soft deleted as well.我正在尝试软删除父项,反过来又希望子项也被软删除。
When I try to soft delete , it sets the deleted
flag to true in both tables and that's what I want.当我尝试软删除时,它会将两个表中的
deleted
标志设置为 true,这就是我想要的。
However, the parent_id
in the child_table
is set to null
when I perform the delete.但是,当我执行删除时,
child_table
的parent_id
设置为null
。 Why is this happening and how can I stop this ?为什么会发生这种情况,我该如何阻止?
The delete operation :删除操作:
Parent parent= entityManager.find(Parent.class, id);
entityManager.remove(parent);
I'm not sure if what you want is possible, but you could try adding this to your mapping:我不确定您想要的是否可行,但您可以尝试将其添加到您的映射中:
@OnDelete(action = OnDeleteAction.NO_ACTION)
Maybe with this Hibernate won't change the relationship.也许这个 Hibernate 不会改变这种关系。
作为解决方法,您可以关闭级联删除并手动删除子项
You need to:你需要:
@OneToMany(cascade = CascadeType.ALL)
with @OneToMany(cascade = CascadeType.PERSIST)
.@OneToMany(cascade = CascadeType.ALL)
替换为@OneToMany(cascade = CascadeType.PERSIST)
。nullable = false
to @JoinColumn(name = "parent_id")
annotation.nullable = false
添加到@JoinColumn(name = "parent_id")
注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.