JPA:DELETE WHERE 不会删除子项并引发异常 [英] JPA: DELETE WHERE does not delete children and throws an exception

查看:23
本文介绍了JPA:DELETE WHERE 不会删除子项并引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 JPQL 查询,我正在尝试从 MOTHER 中删除大量行.

I am trying to delete a large number of rows from MOTHER thanks to a JPQL query.

Mother 类定义如下:

@Entity
@Table(name = "MOTHER")
public class Mother implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "mother", 
               orphanRemoval = true)
    private List<Child> children;    
}

@Entity
@Table(name = "CHILD")
public class Child  implements Serializable {

    @ManyToOne
    @JoinColumn(name = "MOTHER_ID")
    private Mother mother;    
}

如您所见,Mother 类具有子级",并且在执行以下查询时:

As you can see, the Mother class has "children" and when executing the following query:

String deleteQuery = "DELETE FROM MOTHER WHERE some_condition";
entityManager.createQuery(deleteQuery).executeUpdate();

抛出异常:

ERROR - ORA-02292: integrity constraint <constraint name> violated - 
                   child record found

当然,我可以先选择所有要删除的对象,然后将它们检索到列表中,然后再遍历列表删除所有检索到的对象,但是这样的解决方案的性能会很糟糕!

Of course, I could first select all the objects I want to delete and retrieve them into a list before iterating through it to delete all the retrieved object, but the performance of such a solution would just be terrible!

那么有没有办法利用前面的映射来有效地删除所有 Mother 对象和所有与它们关联的 Child 对象,而无需先编写查询所有孩子?

So is there a way to take advantage of the previous mapping to delete all the Mother objects AND all the Child objects associated with them efficiently and without writing first the queries for all the children?

推荐答案

DELETE(和 INSERT)不会通过 JPQL 查询中的关系级联.这在规范中有明确的拼写:

DELETE (and INSERT) do not cascade via relationships in JPQL query. This is clearly spelled in specification:

删除操作只适用于指定类的实体,并且它的子类.它不会级联到相关实体.

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

幸运的是通过实体管理器持久化和移除(当定义了级联属性时).

Luckily persist and removal via entity manager do (when there is cascade attribute defined).

你可以做什么:

  • 获取所有应删除的 Mother 实体实例.
  • 为他们每个人调用 EntityManager.remove().

代码是这样的:

String selectQuery = "SELECT m FROM Mother m WHERE some_condition";  
List<Mother> mothersToRemove = entityManager
    .createQuery(selectQuery)
    .getResultStream()
    .forEach(em::remove);

这篇关于JPA:DELETE WHERE 不会删除子项并引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆