2

我有这些课。

@Entity
@Table(name ="a")
class A{
  private Integer aId;
  private B b;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id_a")
  public Integer getAId() {
return aId;
  }

  @OneToOne(mappedBy = "a", cascade={CascadeType.ALL})
  public B getB() {
        return b;
    }
}

@Entity
@Table (name= "b")
class B{
    private A a;

    @OneToOne
    @JoinColumn(name = "id_a")
    public A getA() {
        return a;
    }

}

表格看起来像:

一)| id_A |....其他字段...|

乙)| id_B | fk_id_A |..其他字段..|

但是,当我尝试删除 A 的一个实例时,我得到了,

org.hibernate.ObjectDeletedException: 已删除的对象将被级联重新保存:(从关联中删除已删除的对象)[B#130]

我尝试在交叉引用上设置 null :

b.setA(null) 
a.setB(null)

但是仍然会抛出异常。

我所做的只是删除 A 中的一行,并将 B 的外键保留为空,但是当我重新尝试删除 B 时,得到同样的错误。

这是我的删除代码:

public static void delete(Object object) throws Exception {
        Transaction tx = getSession().beginTransaction();       
        try {
            getSession().delete(object);
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            getSession().close();
            throw ex;
        }
    }

getSession总是返回一个有效的会话。

有什么我想念的吗?

4

2 回答 2

1

Start from top and continue working down. You need to delete the reference to A in table B. So locate the reference in B of the record you're trying to delete in A and delete that record in B. Then go back to A and delete the record in A.

If you're using SQL Server, you can set cascading delete on table A and this will be done for you automatically. You have to be careful with this though. I wouldn't recommend this for complex structures.

于 2009-07-03T21:33:47.777 回答
0

Are you performing the nulling of cross-references in a separate transaction? Those changes may need to be committed for the delete to work.

于 2009-08-03T04:11:23.117 回答