AnEi
AnEi

Reputation: 335

Hibernate set foreign key to null when delete entity

I have following hibernate entites:

@Entity
@Table(name = "model_view")
public class ModelView {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "modelView_id")
    private Integer id;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "page_id", nullable = false, insertable = true, updatable = true)
    private Page page;

    /* getters and setters */
}

And:

@Entity
public class Page {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "page_id")
    private Integer id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "page_id")
    @IndexColumn(name = "modelView_id")
    private Set<ModelView> modelViews = new HashSet<ModelView>();

    /* getters and setters */
}

When I delete entity «ModelView» in DAO I have exception:

ORA-01407: unable to replace ("MODEL_VIEW"."PAGE_ID") to NULL

What is wrong? Why hibernate set foreign key to NULL before delete?

Upvotes: 21

Views: 23092

Answers (1)

Jesse Webb
Jesse Webb

Reputation: 45243

Why hibernate set foreign key to NULL before delete?

Hibernate tries to dereference the record you are attempting to delete by NULLing out the FK. Unfortunately, in most cases FKs are NOT NULLable. You have to tell Hibernate not to update the ModelView instances when deleting Page records.

Try changing insertable and updatable to false on the @JoinColumn mapping of page in ModelView:

@JoinColumn(name = "page_id", nullable = false, insertable = false, updatable = false)

When using these values, the ModelView records will remain. Again, this won't work if you enforce referential integrity. To get around this, you need to turn on cascading of deletes. I notice that in your code you already are using CascadeType.ALL which should work just fine.

Here is a SO Q&A which explains these fields:

In JPA why and how to use insertable and updatable parameter?

I had a similar problem which was fixed by using false for these values.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

Upvotes: 39

Related Questions