JPA删除所有实体的作品很奇怪 [英] JPA delete all entites works strange
问题描述
我有一个这样的实体关系:
I have an entityrelation like this:
在ParentObj类中:
In the ParentObj class:
@OneToMany(mappedBy = "parentObj", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ChildObj> list;
在ChildObj类中:
In the ChildObj class:
@JoinColumn(name="PARENT_OBJ")
@ManyToOne
private ParentObj parentObj;
当父对象保留或删除时,子对象也将保留/删除. 但是,当我尝试使用CriteriaDelete删除所有实体时,例如:
When the parent object persisted or removed, the child is persisted/removed as well. BUT when I try to remove all the entities with a CriteriaDelete like:
CriteriaDelete<ParentObj> query = builder.createCriteriaDelete(ParentObj.class);
query.from(ParentObj.class);
em.createQuery(query).executeUpdate();
或类似这样的简单查询:
or a simple query like this:
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
我收到了ConstraintViolationException,有人可以解释为什么会这样吗?
我使用的是org.hibernate.ejb. HibernatePersistence 提供程序和 JTA 在 Wildfly 服务器上.
I'm using org.hibernate.ejb.HibernatePersistence provider with JTA on a Wildfly server.
推荐答案
以下
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
是JPQL批量更新命令,并且作为JPQL语言参考说明:
is a JPQL bulk update command and as the JPQL language reference notes:
10.2.9. JPQL批量更新和删除
10.2.9. JPQL Bulk Update and Delete
操作批量更新和删除操作适用于的实体 单一实体类(及其子类,如果有的话).
Operations Bulk update and delete operations apply to entities of a single entity class (together with its subclasses, if any).
删除操作仅适用于指定类的实体,并且 它的子类. 它不会级联到相关实体. ....
A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.....
https://docs.oracle.com/html/E24396_01/ejb3_langref. html#ejb3_langref_bulk_ops
因此,实质上,您正在尝试删除一个实体,由于缺少级联,该实体在数据库中仍将具有FK引用.因此,例外.
So essentially you are attempting to remove an entity which, due to lack of cascading, will still have FK references in the database. Hence the exception.
CriteriaDelete具有类似的限制:
CriteriaDelete has similar limitations:
https://docs.oracle.com/javaee/7/api/javax/persistence/criteria/CriteriaDelete.html
标准API批量删除操作直接映射到数据库删除操作.持久性上下文与 批量删除的结果.
Criteria API bulk delete operations map directly to database delete operations. The persistence context is not synchronized with the result of the bulk delete.
这篇关于JPA删除所有实体的作品很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!