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

孤者浪人 提交于 2020-02-12 09:18:30

问题


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. 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; FKCEC6E942485388AB table: PERSON_EMAIL

If it can be a pure JPA annotation rather than a Hibernate annotation that would be a bonus!


回答1:


I'll let you interpret the part of the JPA 2.0 specification that mentions that a bulk delete operation is not cascaded:

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.

And the fact is that Hibernate won't cascade a delete to a collection table either. This has been reported in HHH-5529 and the suggested approaches are:

You could also (a) clean up the collection table yourself or (b) use cascading foreign keys in the schema.

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).



来源:https://stackoverflow.com/questions/3903202/how-to-do-bulk-delete-in-jpa-when-using-element-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!