Reputation: 45174
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..|
But, when I try to delete an instance of A, I get,
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?
Upvotes: 2
Views: 6628
Reputation: 1934
Are you performing the nulling of cross-references in a separate transaction? Those changes may need to be committed for the delete to work.
Upvotes: 0
Reputation:
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.
Upvotes: 1