Deleting JPA object fails due to foreign key constraints?
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:
2029 [main] ERROR org.hibernate.util.JDBCExceptionReporter - integrity
constraint violation: foreign key no ac开发者_运维百科tion; 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>();
}
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.
And while the JPA spec explicitly writes that a bulk delete is not cascaded to related entities:
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.
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:
- 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.
精彩评论