为什么以下查询会由于外键约束而失败?我没有其他方法可以删除我知道的关联数据。
Query query=em.createQuery("DELETE FROM Person");
query.executeUpdate();
em.getTransaction().commit();
我认为导致问题的违规关系是 activationKey
字段:
2029 [main] ERROR org.hibernate.util.JDBCExceptionReporter - integrity
constraint violation: foreign key no action; FKCEC6E942485388AB
table: ACTIVATION_KEY
这是我现在拥有的:
@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>();
}
最佳答案
Why would the following query fail due to a foreign key constraint?
看起来您的批量删除查询没有从集合表中删除条目,因此违反了 FK 约束。
虽然 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.
这不完全是你的情况,我认为你想做的事情应该得到支持。
您可能面临 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
我建议提出一个问题。
解决方法:使用原生查询删除集合表,然后删除实体表。
关于java - 由于外键约束,删除 JPA 对象失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627674/