[英]Hibernate unidirectional OneToMany delete violates constraint ( optional=false at parent side?)
I use Hibernate 3.6 and I have something like this: 我使用Hibernate 3.6,我有这样的东西:
@Entity
public class Parent {
@OnyToMany( fetch = FetchType.LAZY, cascade = { ascadeType.ALL } )
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE )
@JoinColumn( name="Parent_ID" )
public List<Child> getChildren() { return children; }
public void setChildren( List<Child> children ) { this.children = children; }
private transient List<TitleMetadataCategory> children;
...
}
@Entity
public class Child {
....
}
Association is unidirectional for several reasons and I don't want to change it . 由于几个原因,关联是单向的,我不想改变它。 In addition orphan children don't exist, so there is DB constraint that CHILD.PARENT_ID is not null.
另外孤儿子不存在,因此存在DB约束,即CHILD.PARENT_ID不为空。 All works fine, except removing child.
一切正常,除了去除孩子。 When I do
当我做
parent.getChildren().remove(child); session.saveOrUpdate(parent)
parent.getChildren().remove(child); session.saveOrUpdate(parent)
. parent.getChildren().remove(child); session.saveOrUpdate(parent)
。
it fails. 它失败。
Since I don't have 既然我没有
@ManyToOne( optional=false )
at the child side Hibernate tries to update child with PARENT_ID=NULL and fails due to DB constraint. 在子端,Hibernate尝试更新PARENT_ID = NULL的子节点,并由于DB约束而失败。
Is there any way to fix it? 有什么办法可以解决吗?
Have you tried 你有没有尝试过
@JoinColumn(name = "Parent_ID", nullable = false)
? ?
Also, note that attached entities are automatically persistent. 另请注意,附加实体是自动持久的。 You don't need to call
saveOrUpdate()
. 您不需要调用
saveOrUpdate()
。
The answer of JB Nizet is working, but with one correction. JB Nizet的答案正在发挥作用,但只有一次修正。 Since I also have Child.getParentId() method ( not getParent() ), its Column annotation should have
nullable=false, insertable=false, updateble=false
parameters in addition to nullable=false, updatable=false
in Parent.getChildren() association. 由于我也有Child.getParentId()方法(不是getParent()),因此除了
nullable=false, updatable=false
在Parent.getChildren()中,它的Column注释应该有nullable=false, insertable=false, updateble=false
参数。协会。
With the current configuration Hibernate doesn't know that the Child
has to be deleted when you remove it from children
collection (it's called orphan removal). 随着当前配置Hibernate不知道
Child
已被删除,当你从删除它children
集合(这就是所谓的孤儿去除)。 You need @OneToMany(orphanRemoval=true)
in the parent. 在父级中需要
@OneToMany(orphanRemoval=true)
。 org.hibernate.annotations.CascadeType.DELETE
only specifies that child should be deleted too when the entire parent is deleted. org.hibernate.annotations.CascadeType.DELETE
仅指定在删除整个父项时也应删除子项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.