删除实体时,Hibernate将外键设置为null [英] Hibernate set foreign key to null when delete entity
问题描述
我有以下冬眠动物:
@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 */
}
并且:
@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 */
}
当我在DAO中删除实体«ModelView»时,我有一个例外:
When I delete entity «ModelView» in DAO I have exception:
ORA-01407: unable to replace ("MODEL_VIEW"."PAGE_ID") to NULL
怎么了?为什么冬眠在删除之前将外键设置为NULL?
What is wrong? Why hibernate set foreign key to NULL before delete?
推荐答案
为什么在删除之前休眠将外键设置为NULL?
Why hibernate set foreign key to NULL before delete?
Hibernate通过使FK无效来尝试取消引用您要删除的记录.不幸的是,在大多数情况下,FK不能为空.您必须告诉Hibernate在删除Page
记录时不要更新ModelView
实例.
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.
尝试在ModelView
中的page
的@JoinColumn
映射上将insertable
和updatable
更改为false:
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)
使用这些值时,ModelView
记录将保留.同样,如果您强制执行参照完整性,则此操作将无效.要解决此问题,您需要打开级联删除操作.我注意到在您的代码中您已经在使用CascadeType.ALL
,它应该可以正常工作.
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.
以下是SO Q& A,其中解释了以下字段:
Here is a SO Q&A which explains these fields:
我有一个类似的问题,可以通过对这些值使用false
来解决.
I had a similar problem which was fixed by using false
for these values.
如何映射"insert ='false'update ='false'"在一个复合ID密钥属性中,该属性也可用于一对多FK?
这篇关于删除实体时,Hibernate将外键设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!