Hibernate unidirectional OneToMany delete violates

2020-07-29 17:24发布

问题:

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.