java 如何级联删除属于 jpa 实体的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7695831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I cascade delete a collection which is part of a jpa entity?
提问by emt14
@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:
这总是无法删除实体并出现以下错误:
The DELETE statement conflicted with the REFERENCE constraint "FK966F0D9A66DB1E54". The conflict occurred in database "TFADB", table "dbo.MonthlyReport_categories", column 'MonthlyReport_id'.
DELETE 语句与 REFERENCE 约束“FK966F0D9A66DB1E54”冲突。冲突发生在数据库“TFADB”、表“dbo.MonthlyReport_categories”、“MonthlyReport_id”列中。
How can I specify the mapping so the elements from the categories collection get delete when the report is deleted?
如何指定映射以便在删除报告时删除类别集合中的元素?
回答by Mikko Maunu
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.
级联删除(以及一般的级联操作)仅在通过EntityManager
. 当删除是通过 JP QL / HQL 查询批量删除时,则不会。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
.
ElementCollection
注解没有级联属性,因为操作总是级联的。当您通过 删除实体时EntityManager.remove()
,操作将级联到ElementCollection
.
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.
您必须获取MonthlyReport
要删除的所有实体并EntityManager.remove
为每个实体调用。看起来你也可以在实体中调用 delete-method 来代替 Play 框架中的这个。
回答by J.T.
We found the magic ticket! Add OnDelete(action= OnDeleteAction.CASCADE)to the ElementCollection. This allows us to remove the item from SQL (outside of the entityManager).
我们找到了神奇的票!将OnDelete(action= OnDeleteAction.CASCADE)添加到 ElementCollection。这允许我们从 SQL 中删除项目(在 entityManager 之外)。