【问题标题】:Hibernate how to remove item from list休眠如何从列表中删除项目
【发布时间】:2011-03-25 03:50:38
【问题描述】:

在理解 hibernate 中列表的管理方式方面,我一直面临一些挑战。

我看过以下帖子: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);
}

因此,通过上述设置,第一次在数据库中正确创建了所有内容。第二次,我的期望是集合中的第一组项目将被删除,只有新项目会在数据库中。那没有发生。子项中的原始项与新项一起存在,并且序列号再次从 0 开始。

另外,我看到以下错误

org.hibernate.HibernateException:拥有的实体实例不再引用具有 cascade="all-delete-orphan" 的集合:

我错过了什么。

【问题讨论】:

    标签: java hibernate hibernate-annotations


    【解决方案1】:

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

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

    【讨论】:

    • 成功了 - 需要复习以确保我完全理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2016-03-12
    相关资源
    最近更新 更多