Hibernate单向OneToMany删除违反约束(可选=在父级侧为false) [英] Hibernate unidirectional OneToMany delete violates constraint ( optional=false at parent side?)

查看:272
本文介绍了Hibernate单向OneToMany删除违反约束(可选=在父级侧为false)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @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(){返回孩子; }
public void setChildren(List< Child> children){this.children = children; }
私有瞬态列表< TitleMetadataCategory>儿童;
...
}

@实体
公共类子元素{
....
}

由于几个原因,关联是单向的,我不想改变它。另外孤儿不存在,所以有CHILD.PARENT_ID不为空的DB约束。
一切正常,除去孩子。当我做的时候



parent.getChildren()。remove(child);
session.saveOrUpdate(父)


失败。



因为我没有

  @ManyToOne(可选=假)

在子节点Hibernate尝试用PARENT_ID = NULL更新子节点,并且由于DB约束而失败。

有没有什么办法可以解决它?

解决方案

你试过了

pre $ @ code @JoinColumn(name =Parent_ID,nullable = false)



另外请注意,连接的实体自动持久化。您无需调用 saveOrUpdate()


I use Hibernate 3.6 and I have something like this:

@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. All works fine, except removing child. When I do

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.

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().

这篇关于Hibernate单向OneToMany删除违反约束(可选=在父级侧为false)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆