Phate
Phate

Reputation: 6612

OneToMany: hibernate tries to nullify external reference instead of deleting whole child

I have an entity "BigList" containing a list of elements:

  @OneToMany( fetch = FetchType.LAZY, orphanRemoval=true )
  @Cascade( { CascadeType.ALL } )  
  @JoinColumn( name = "ID_LIST", referencedColumnName="ID", updatable=true, insertable=true )
  @OrderBy( value="position asc")
  List<BigListElem> elements;

While a BigListElem has this reference:

  @ManyToOne( optional=false )
  @NotFound( action=NotFoundAction.EXCEPTION )
  @JoinColumn( name="ID_LIST", nullable=false, updatable=true, insertable=true  )
  private BigList list;

Now, if I delete one single element of this list and call merge() method (thus updating) I get the following exception:

impossible update ("DBNAME"."BIG_LIST_ELEM"."ID_LIST") to NULL

In other words instead of deleting the children it tries to set the external reference to null, leading to exception because "nullable" is set to false. This is correct, because external reference cannot be null...problem is that I am not asking to set this reference to null but deleting the whole element!

Why is that?

Upvotes: 1

Views: 179

Answers (1)

WeMakeSoftware
WeMakeSoftware

Reputation: 9162

Usually FK constraints on children elements are nullable, because hibernate if I remember correctly does the deletion in this way:

  1. set the FK of child entity to null
  2. delete the child entity

So if you enforce the not-null constraint on the database level, you will have to manually delete the entity from the DB.

Upvotes: 2

Related Questions