从一对多集合中删除元素(Java + HIbernate + Struts)

Pet*_*cco 5 java collections struts hibernate

我无法从数据库中删除子对象.从org.apache.struts.action.Action.execute()方法中,我将孩子从父母那里移走List,并且还要打电话session.delete(child).我简化了下面的代码,只包含了我认为相关的内容.


Hibernate Mapping

<class 
    name="xxx.xxx.hibernate.Parent" 
    table="parent">

    ...

    <list
        name="children"
        cascade="all,delete-orphan"
        lazy="true"
        inverse="true">

        <key column="parent_id"/>
        <index column="list_index"/>
        <one-to-many class="xxx.xxx.hibernate.Child"/>
    </list>
</class>

<class 
    name="xxx.xxx.hibernate.Child" 
    table="child">

    ...

    <many-to-one
        name="parent"
        class="xxx.xxx.hibernate.Parent"
        not-null="true"
        column="parent_id" />

</class>
Run Code Online (Sandbox Code Playgroud)


摘自execute()方法

Transaction tx = session.beginTransaction();  //session is of type org.hibernate.Session

try {
    Parent parent = (Parent) session.get(Parent.class, getParentId());

    Iterator i = form.getDeleteItems().iterator();  //form is of type org.apache.struts.action.ActionForm
    while(i.hasNext()){
        Child child = (Child) i.next();
        session.delete(child);
        parent.getChildren().remove(child); //getChildren() returns type java.util.List
    }

    session.saveOrUpdate(parent);
    tx.commit();
} ...
Run Code Online (Sandbox Code Playgroud)


我只尝试过,session.delete(child);我只尝试过parent.getChildren().remove(child);两条线,都没有成功.没有错误或抛出的异常或任何类型的东西.我确信这个代码被调用(我甚System.out.println();至用来追踪正在发生的事情),但数据库没有更新.我可以使用类似的代码添加子项,编辑现有子项的非集合属性,编辑父项的属性,所有这些都有效,只是不删除!

根据Hibernate常见问题我正在进行映射,根据这个问题,我有正确的逻辑.我看了整个互联网,似乎找不到任何其他东西.

我究竟做错了什么?请帮忙!谢谢.


版本说明

一切都有几年了:

  • Java 1.4.2
  • SQL Server 2005
  • Hibernate 3.0.5
  • Struts 1.2.7
  • Apache Tomcat 5.0.28

Boz*_*zho 6

如果您没有覆盖该equals()方法,则可能在列表中找不到该实体,因为它已被分离,现在是另一个实例.这就是为什么remove不起作用.然后,即使delete工作,对象也会重新进行cascacde,因为它们仍然存在于集合中.这是做什么的:

  • 使用(简单)或某种类型的业务键(更合适)覆盖equals()(和hashCode())方法(id搜索stackoverflow以获取覆盖这两个方法的提示),并仅保留getChildren().remove(child)
  • 在第一个循环中迭代子集合,如下所示:

    Iterator<Child> i = form.getDeleteItems().iterator();
    while(i.hasNext()){
        Child child = i.next();
        for (Iterator<Child> it = parent.getChildren().iterator();) {
             if (child.getId().equals(it.next().getId()) {
                 it.remove(); // this removes the child from the underlying collection
             }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)