Hibernate在一对多关系中删除集合的成员

时间:2013-05-09 04:34:53

标签: java hibernate

我知道这是Hibernate的一个相当普遍的问题,但是我仍然在努力编写能够正常运行的代码。基本上,我有两个班级;人口统计和NextOfKin。后者与人口统计学作为一对多集相关。简化为:

<hibernate-mapping>
          <class name="entities.Demographic" table="Demographics">

            <id name="id" type="long" column="Id" ><generator class="identity"/></id>
            <set name="nextOfKinList" table="NextOfKin" inverse="true" lazy="true" fetch="select" cascade="all,delete-orphan" >
                <key><column name="DemographicId" not-null="true" /></key>
                <one-to-many class="entities.NextOfKin" />
            </set>
         </class>
</hibernate-mapping>


<hibernate-mapping>
        <class name="entities.NextOfKin" table="NextOfKin">
            <id name="id" type="long" column="Id" ><generator class="identity"/></id>  
            <many-to-one name="demographic" class="entities.Demographic" fetch="select">
                <column name="DemographicId" not-null="true" />
            </many-to-one>
</hibernate-mapping>

我试图使用的代码删除了NextOfKin的列表 - 再次简化:

    try {
        DAOFactory factory = DAOFactory.instance(DAOFactory.HIBERNATE);
        HibernateUtil.beginTransaction();
        Demographic demographic = factory.getDemographicDAO().findDemographic();        

        if (!demographic.getNextOfKinList().isEmpty()) {
            for (Iterator<NextOfKin> iterator = demographic.getNextOfKinList().iterator(); iterator.hasNext();) {
                NextOfKin nextOfKin = iterator.next();
                factory.getNextOfKinDAO().delete(nextOfKin);
                iterator.remove();
            }
        }
        demographic.setNextOfKinList(nextOfKinList);
        HibernateUtil.commitTransaction();
    }
    catch (Exception e) {
        e.printStackTrace();
        HibernateUtil.rollbackTransaction();
    }
    finally {
        HibernateUtil.closeSession();
    }

我尝试了几种方法,但是所有方法都失败了要么保持关系完整,要么就像当前示例抛出异常一样:

org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: entities.Demographic.nextOfKinList

道歉,因为这是一个相当标准的问题,但任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

您只需要清除设置:demographic.getNextOfKinList().clear()。 Hibernate会自动删除数据库中的元素,这是delete-orphan的作用。

if (!demographic.getNextOfKinList().isEmpty()) {
     demographic.getNextOfKinList().clear();      
}

删除行:demographic.setNextOfKinList(nextOfKinList);如果要向集合中添加新元素,请将它们添加到现有集合中:

demographic.getNextOfKinList().add(newElem)

答案 1 :(得分:1)

不要一个一个地删除它们,而是试试这个。

demographic.getNextOfKinList().clear();

demographic.getNextOfKinList().addAll(nextOfKinList);