views:

994

answers:

3

Hi all, I have these classes.

@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;
    }

}

And tables look like:

A) | id_A |....other fields...|

B) | id_B | fk_id_A |..other fields..|

The thing is that when I try to delete an instance of A, i get thrown

org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade : (remove deleted object from associations)[B#130]

I've tried setting null on cross references:

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

but exception still gets thrown.

All that I have accomplished is to delete a row in A, and leave B's foreign Key null, but when i re try to delete B, get the same error.

This is my delete code:

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 always returns a valid session.

Is there anything i'm missing? Im starting to lose my mind with this.

+1  A: 

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.

Sergey
A: 

did you try to add "DELETE-ORPHAN" to your cascading?

Chris
I did. I get to delete instance from A, but fail to delete instance from B. It just nulls the foreign key and launchs an exception.
Tom
A: 

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

jwaddell