简体   繁体   English

使用元素集合时如何在 JPA 中进行批量删除?

[英]How to do bulk delete in JPA when using Element Collections?

I am having trouble working out how to do a bulk delete of a Person object using JPA, when the Person objects contain data stored using an @ElementCollection .Person对象包含使用@ElementCollection存储的数据时,我无法确定如何使用 JPA 批量删除Person对象。 Any ideas on how to do this would be much appreciated.关于如何做到这一点的任何想法将不胜感激。

@Entity
@Table(name="at_person")
public class Person implements Comparable<Person> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private long id = 0;

    @Column(name="name", nullable = true, length = 128)
    private String name = "";

    @ElementCollection
    @Column(name = "email")
    @CollectionTable(name = "person_email", joinColumns = @JoinColumn(name = "person_id"))
    private Set<String> email = new HashSet<String>();
}

What I am doing at the moment is this, and it fails with a foreign key constraint error:我现在正在做的是这个,它因外键约束错误而失败:

Query query=em.createQuery("DELETE FROM Person");

Caused by: java.sql.SQLException: integrity constraint violation: foreign key no action;引起:java.sql.SQLException:违反完整性约束:外键无动作; FKCEC6E942485388AB table: PERSON_EMAIL FKCEC6E942485388AB 表:PERSON_EMAIL

If it can be a pure JPA annotation rather than a Hibernate annotation that would be a bonus!如果它可以是纯 JPA 注释而不是 Hibernate 注释,那将是一个奖励!

I'll let you interpret the part of the JPA 2.0 specification that mentions that a bulk delete operation is not cascaded:我将让您解释 JPA 2.0 规范中提到批量删除操作不是级联的部分:

4.10 Bulk Update and Delete Operations 4.10 批量更新和删除操作

... ...

A delete operation only applies to entities of the specified class and its subclasses.删除操作仅适用于指定类及其子类的实体。 It does not cascade to related entities .它不会级联到相关实体

And the fact is that Hibernate won't cascade a delete to a collection table either.事实是 Hibernate 也不会级联删除到集合表。 This has been reported in HHH-5529 and the suggested approaches are:这已在HHH-5529 中报告,建议的方法是:

You could also (a) clean up the collection table yourself or (b) use cascading foreign keys in the schema.您还可以 (a) 自己清理集合表或 (b) 在架构中使用级联外键。

In other words, (a) use native SQL or (b) use a cascade delete constraint at the database level - and you'll have to add it manually, I don't think you can use @OnDelete with the @ElementCollection annotation (same story as HHH-4301 IMO).换句话说,(a) 使用本机 SQL 或 (b) 在数据库级别使用级联删除约束 - 您必须手动添加它,我认为您不能将@OnDelete@ElementCollection注释一起使用(与HHH-4301 IMO 相同的故事)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM