我使用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 {
....
}
关联是单向的,有几个原因,我不想改变它。另外孤儿子不存在,因此存在DB约束,即CHILD.PARENT_ID不为空。 一切正常,除了去除孩子。当我做的时候
parent.getChildren().remove(child);
session.saveOrUpdate(parent)
。
失败了。
因为我没有
@ManyToOne( optional=false )
在子端,Hibernate尝试更新PARENT_ID = NULL的子节点,并因DB约束而失败。
有没有办法解决它?
答案 0 :(得分:3)
你试过吗
@JoinColumn(name = "Parent_ID", nullable = false)
另外,请注意附加的实体是自动持久的。您无需致电saveOrUpdate()
。
答案 1 :(得分:1)
JB Nizet的答案正在发挥作用,但只有一次修正。由于我也有Child.getParentId()方法(不是getParent()),因此除了Parent.getChildren()关联中的nullable=false, insertable=false, updateble=false
之外,其Column注释应该有nullable=false, updatable=false
个参数。
答案 2 :(得分:0)
使用当前配置,当您从Child
集合中删除它时,Hibernate不知道必须删除children
(它被称为孤立删除)。父母需要@OneToMany(orphanRemoval=true)
。 org.hibernate.annotations.CascadeType.DELETE
仅指定在删除整个父项时也应删除子项。