2011-03-24 32 views
1

我一直在理解如何在休眠中管理列表。休眠如何从列表中删除项目

我看了以下帖子:hibernate removing item from a list does not persist,但没有帮助。

因此,这里的家长:

public class Material extends MappedModel implements Serializable 
{ 
    /** 
    * List of material attributes associated with the given material 
    */ 
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
    @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) 
    @JoinColumn(name = "material_id", nullable = false) 
    @org.hibernate.annotations.IndexColumn(name = "seq_number", base = 0) 
    private List<MaterialAttribute> materialAttributes = new ArrayList<MaterialAttribute>(); 

这里是孩子

公共类MaterialAttribute扩展MappedModel实现Serializable

{ 
    /** 
    * identifies the material that these attributes are associated with 
    */ 
    @ManyToOne 
    @JoinColumn(name = "material_id", nullable=false, updatable=false, insertable=false) 
    private Material material; 

所以在我的服务类我做了以下内容:

public void save(MaterialCommand pCmd) 
{ 
Material material = new Material(); 
if(null != pCmd.getMaterialId()) 
{ 
    material = this.loadMaterial(pCmd.getMaterialId()); 
} 

material.setName(pCmd.getName()); 
material.getMaterialAttributes().clear(); 

    List<MaterialAttribute> attribs = new ArrayList<MaterialAttribute>(); 
    if(CollectionUtils.isNotEmpty(pCmd.getAttribs())) 
    { 
     Iterator<MaterialAttributeCommand> iter = pCmd.getAttribs().iterator(); 
     while(iter.hasNext()) 
     { 
MaterialAttributeCommand attribCmd = (MaterialAttributeCommand) iter.next(); 
      if (StringUtils.isNotBlank(attribCmd.getDisplayName())) 
{ 
     MaterialAttribute attrib = new MaterialAttribute(); 
     attrib.setDisplayName(attribCmd.getDisplayName()); 
     attrib.setValidationType(null); 
     attribs.add(attrib); 
} 
     } 
    } 

    material.setMaterialAttributes(attribs); 
    this.getMaterialDao().update(material); 
} 

因此,在上面第一次创建数据库时,正确地创建了一切。第二次,我的期望是集合中的第一组项目将被删除,只有新项目将在数据库中。那没有发生。子项中的原始项目与新项目一起存在,并且seq编号从0开始。

而且,我看到下面的错误

org.hibernate.HibernateException:与级联集合=“全删除,孤儿”由所拥有的实体实例不再被引用:

上午什么我想念。

回答

4

DELETE_ORPHAN的实施对收集操作应用了一些限制。特别是,您不应该用另一个集合实例替换该集合。相反,将新项目添加到现有集合中:

material.getMaterialAttributes().clear(); 
... 
material.getMaterialAttributes().addAll(attribs); 
+0

这样做 - 将需要审查以确保我有充分的理解。 – boyd4715 2011-03-24 20:27:27