我正在尝试删除包含实体地图的实体,如下所示:
@Entity
public class TrxReport extends Model {
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "StatCategory")
@MapKeyColumn(name = "TrxReport_key", nullable = false)
@Cascade(value = { CascadeType.ALL })
public Map<String, TrxStatCategory> categories;
@Override
public TrxReport delete(){
for (AtmPosTrxStatCategory cat : categories.values()) {
if (cat != null){
categories.remove(cat.name);
cat.delete();
}
}
super.delete();
return this;
}
}
但是,我总是会在StatCategory表上抱怨约束违规错误抱怨categories_id。 删除是否需要使用自定义查询完成,还是可以像上面那样实现?
答案 0 :(得分:1)
我认为您收到错误,因为您尝试删除的类别因CascadeType.ALL
而被删除两次。如果您使用orphanRemoval
,则TrxStatCategory
如果从categories
中的TrxReport
集合中移除,也会被删除。
如果使用orphanRemoval
,而不是覆盖delete()
:
@Entity
public class TrxReport extends Model {
@CollectionTable(name = "StatCategory")
@MapKeyColumn(name = "TrxReport_key", nullable = false)
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
public Map<String, TrxStatCategory> categories;
}