如何级联删除属于 JPA 实体的集合? [英] How can I cascade delete a collection which is part of a JPA entity?
问题描述
@Entity
public class Report extends Model {
public Date date;
public double availability;
@ElementCollection
@Cascade(value={CascadeType.ALL})
public Map<FaultCategory, Integer> categories;
}
在我的一项工作中,我有以下代码:
In one of my jobs I have the following code:
int n = MonthlyReport.delete("date = ?", date);
这总是无法删除实体并出现以下错误:
This always fails to delete the entity with the following error:
DELETE 语句与 REFERENCE 约束FK966F0D9A66DB1E54"冲突.冲突发生在数据库TFADB"、表dbo.MonthlyReport_categories"、MonthlyReport_id"列中.
The DELETE statement conflicted with the REFERENCE constraint "FK966F0D9A66DB1E54". The conflict occurred in database "TFADB", table "dbo.MonthlyReport_categories", column 'MonthlyReport_id'.
如何指定映射以便在删除报告时删除 categories
集合中的元素?
How can I specify the mapping so the elements from the categories
collection get deleted when the report is deleted?
推荐答案
级联删除(以及一般的级联操作)仅在通过 EntityManager
完成操作时有效.当删除是通过 JP QL/HQL 查询批量删除时,则不会.当通过查询完成删除时,您不能指定将删除链接到 ElementCollection
中的元素的映射.
Cascading delete (and cascading operations in general) is effective only when operation is done via EntityManager
. Not when delete is done as bulk delete via JP QL /HQL query. You cannot specify mapping that would chain removal to the elements in ElementCollection
when removal is done via query.
ElementCollection
注释没有级联属性,因为操作总是级联的.当您通过 EntityManager.remove()
删除实体时,操作将级联到 ElementCollection
.
ElementCollection
annotation does not have cascade attribute, because operations are always cascaded. When you remove your entity via EntityManager.remove()
, operation is cascaded to the ElementCollection
.
您必须获取要删除的所有 MonthlyReport
实体,并为每个实体调用 EntityManager.remove
.看起来你也可以在实体中调用 delete-method 来代替 Play 框架中的这个.
You have to fetch all MonthlyReport
entities you want to delete and call EntityManager.remove
for each of them. Looks like instead of this in Play framework you can also call delete-method in entity.
这篇关于如何级联删除属于 JPA 实体的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!