java 由于外键限制,删除 JPA 对象失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3627674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting JPA object fails due to foreign key constraints?
提问by Jacob
Why would the following query fail due to a foreign key constraint? There is no other way for me to delete the associated data that I am aware of.
为什么以下查询会由于外键约束而失败?我没有其他方法可以删除我知道的相关数据。
Query query=em.createQuery("DELETE FROM Person");
query.executeUpdate();
em.getTransaction().commit();
The I believe the offending relationship causing the problem is the activationKey
field:
我认为导致问题的违规关系是以下activationKey
领域:
2029 [main] ERROR org.hibernate.util.JDBCExceptionReporter - integrity
constraint violation: foreign key no action; FKCEC6E942485388AB
table: ACTIVATION_KEY
This is what I have now:
这就是我现在所拥有的:
@Entity
@Table(name="person")
public class Person implements Comparable<Person> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private long id = 0;
@ElementCollection
@Column(name = "activation_key")
@CollectionTable(name = "activation_key")
private Set<String> activationKey = new HashSet<String>();
}
回答by Pascal Thivent
Why would the following query fail due to a foreign key constraint?
为什么以下查询会由于外键约束而失败?
It looks like your bulk delete query is not deleting the entries from the collection table, hence the FK constraint violation.
看起来您的批量删除查询并未从集合表中删除条目,因此违反了 FK 约束。
And while the JPA spec explicitly writes that a bulk delete is not cascaded to related entities:
虽然 JPA 规范明确指出批量删除不会级联到相关实体:
4.10 Bulk Update and Delete Operations
...
A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.
4.10 批量更新和删除操作
...
删除操作仅适用于指定类及其子类的实体。它不会级联到相关实体。
That's not exactly your case and I think that what you want to do should be supported.
这不完全是你的情况,我认为你想做的事情应该得到支持。
You're probably facing one of the limitation of Hibernate's bulk delete, see for example:
您可能正面临 Hibernate 批量删除的限制之一,例如:
- HHH-3337 - Hibernate disregards @JoinTable when generating bulk UPDATE/DELETE for a self-joined entity
- HHH-1917 - Bulk Delete on the owning side of a ManyToMany relation needs to delete corresponding rows from the JoinTable
I suggest raising an issue.
我建议提出一个问题。
Workaround: use native queries to delete the collection table and then the entity table.
解决方法:使用本机查询删除集合表,然后删除实体表。