2012-03-03 56 views
1

我想删除它包含地图实体的如下实体:如何删除一个持久的地图元素与JPA

@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 。 是否需要使用自定义查询完成删除操作,还是可以像上面那样实现删除操作?

回答

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; 

} 
+0

我不认为地图实体可以使用持久兴田@OneToMany批注 – emt14 2012-03-03 13:03:04

+0

您是否尝试过使用它与[@MapKey(HTTP: //docs.oracle.com/javaee/6/api/javax/persistence/MapKey.html)? – maartencls 2012-03-03 13:10:30

+0

难道你不能让它成为一对多的,那么有一个独立的属性是只读的吗? – Zoidberg 2012-03-03 13:17:37