@Entity
public class Report extends Model {
public Date date;
public double availability;
@ElementCollection
@Cascade(value={CascadeType.ALL})
public Map<FaultCategory, Integer> categories;
}
在我的一项工作中,我有以下代码:
int n = MonthlyReport.delete("date = ?", date);
这总是无法删除包含以下错误的实体:
删除语句与引用约束"FK966F0D9A66DB1E54“冲突。冲突发生在数据库"TFADB“、表"dbo.MonthlyReport_categories”、列'MonthlyReport_id‘中。
如何指定映射,以便在删除报表时删除categories
集合中的元素?
发布于 2011-10-08 10:16:44
级联删除(通常是级联操作)只有在通过EntityManager
完成操作时才有效。不是当删除是作为大容量删除通过JP QL /HQL查询。当通过查询完成删除时,不能指定将链式移除到ElementCollection
中元素的映射。
ElementCollection
注释没有级联属性,因为操作总是级联的。通过EntityManager.remove()
删除实体时,操作将级联到ElementCollection
。
您必须获取要删除的所有MonthlyReport
实体,并为每个实体调用EntityManager.remove
。看起来,在Play框架中,您也可以在实体中调用delete-方法,而不是这样。
发布于 2020-07-11 11:00:07
in .提供的答案是正确的,但对我和sebge2来说都是不完整的,正如他/她在评论中指出的那样。@ElementCollection
和@OnDelete
的结合进一步需要@JoinColumn()
。
后续例子:
@Entity
public class Report extends Model {
@Id
@Column(name = "report_id", columnDefinition = "BINARY(16)")
public UUID id; // Added for the sake of this entity having a primary key
public Date date;
public double availability;
@ElementCollection
@CollectionTable(name = "report_category", joinColumns = @JoinColumn(name = "report_id")) // choose the name of the DB table storing the Map<>
@MapKeyColumn(name = "fault_category_key") // choose the name of the DB column used to store the Map<> key
@Column(name = "fault_category_value") // choose the name of the DB column used to store the Map<> value
@JoinColumn(name = "report_id") // name of the @Id column of this entity
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(value={CascadeType.ALL})
public Map<FaultCategory, Integer> categories;
}
此设置将创建一个名为report
的表和另一个具有三列的表report_category
:report_id, fault_category_key, fault_category_value
。report_category.report_id
和report.report_id
之间的外键约束将是ON DELETE CASCADE
。我用Map测试了这个设置。
发布于 2018-10-05 14:38:29
我们找到了魔法券!将OnDelete(action= OnDeleteAction.CASCADE)添加到ElementCollection。这允许我们从SQL (entityManager之外)删除项。
https://stackoverflow.com/questions/7695831
复制相似问题