Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate set foreign key to null when delete entity

Tags:

hibernate

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?

like image 545
AnEi Avatar asked Jun 11 '13 16:06

AnEi


1 Answers

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?

like image 115
Jesse Webb Avatar answered Nov 06 '22 10:11

Jesse Webb