JPA 删除所有实体工作奇怪
JPA delete all entites works strange
我有一个这样的实体关系:
在ParentObj中class:
@OneToMany(mappedBy = "parentObj", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ChildObj> list;
在 ChildObj 中 class:
@JoinColumn(name="PARENT_OBJ")
@ManyToOne
private ParentObj parentObj;
当父对象保留或删除时,子对象也是 persisted/removed。
但是 当我尝试使用 CriteriaDelete 删除所有实体时,例如:
CriteriaDelete<ParentObj> query = builder.createCriteriaDelete(ParentObj.class);
query.from(ParentObj.class);
em.createQuery(query).executeUpdate();
或像这样的简单查询:
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
我遇到了 ConstraintViolationException,有人可以解释为什么会这样吗?
我正在使用 org.hibernate.ejb.HibernatePersistence 提供程序和 JTA
在 Wildfly 服务器上。
以下
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
是一个 JPQL 批量更新命令,作为 JPQL 语言参考注释:
10.2.9。 JPQL 批量更新和删除
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 引用。因此例外。
CriteriaDelete 具有类似的限制:
https://docs.oracle.com/javaee/7/api/javax/persistence/criteria/CriteriaDelete.html
Criteria API bulk delete operations map directly to database delete operations. The persistence context is not synchronized with the
result of the bulk delete.
我有一个这样的实体关系:
在ParentObj中class:
@OneToMany(mappedBy = "parentObj", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ChildObj> list;
在 ChildObj 中 class:
@JoinColumn(name="PARENT_OBJ")
@ManyToOne
private ParentObj parentObj;
当父对象保留或删除时,子对象也是 persisted/removed。 但是 当我尝试使用 CriteriaDelete 删除所有实体时,例如:
CriteriaDelete<ParentObj> query = builder.createCriteriaDelete(ParentObj.class);
query.from(ParentObj.class);
em.createQuery(query).executeUpdate();
或像这样的简单查询:
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
我遇到了 ConstraintViolationException,有人可以解释为什么会这样吗?
我正在使用 org.hibernate.ejb.HibernatePersistence 提供程序和 JTA 在 Wildfly 服务器上。
以下
em.createQuery("DELETE FROM ParentObj po").executeUpdate();
是一个 JPQL 批量更新命令,作为 JPQL 语言参考注释:
10.2.9。 JPQL 批量更新和删除
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 引用。因此例外。
CriteriaDelete 具有类似的限制:
https://docs.oracle.com/javaee/7/api/javax/persistence/criteria/CriteriaDelete.html
Criteria API bulk delete operations map directly to database delete operations. The persistence context is not synchronized with the result of the bulk delete.