Hibernate set foreign key to null when delete entity

后端 未结 1 824
你的背包
你的背包 2021-02-04 05:37

I have following hibernate entites:

@Entity
@Table(name = \"model_view\")
public class ModelView {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
           


        
1条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 06:31

    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?

    0 讨论(0)
提交回复
热议问题