Hibernate unidirectional OneToMany delete violates constraint ( optional=false at parent side?)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 12:25:04

问题


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?


回答1:


Have you tried

@JoinColumn(name = "Parent_ID", nullable = false)

?

Also, note that attached entities are automatically persistent. You don't need to call saveOrUpdate().




回答2:


The answer of JB Nizet is working, but with one correction. 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.




回答3:


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). You need @OneToMany(orphanRemoval=true) in the parent. org.hibernate.annotations.CascadeType.DELETE only specifies that child should be deleted too when the entire parent is deleted.



来源:https://stackoverflow.com/questions/14380167/hibernate-unidirectional-onetomany-delete-violates-constraint-optional-false-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!