Reputation: 27
I have some code that deletes a row from a table using the following code:
EntityManager em = getEntityManager();
try
{
final EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.remove(data);
transaction.commit();
} catch (final PersistenceException e) {
{
throw new CPDPersistenceException(e);
}
The error message is: Cannot delete or update a parent row: a foreign key constraint fails.....etc.
The problem is that a foreign key for other tables "reference_id" exists in the table that I am trying to delete. However, wherever this primary key exists in the persistent Java object where it is defined, it has a reference that should cause cascading deletion. For example:
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="reference_id")
private Reference reference;
My understanding, from reading other entries on this subject, is that the "cascade" phrase attached to reference would fix the problem of deleting one entry that is related to other entries in other tables. Does anybody have any ideas?
Upvotes: 0
Views: 842
Reputation: 61
You are using unidirectional hibernate relationship. And because you are using cascade property for the reference field of both Uuid and Attachment entities, just manipulations on these two entities affect Reference entity, not vice versa. I recommend using bidirectional relationship and set the cascade property of the @OneToMany annotation for your both uuid and attachment fields in your Reference entity to get the desired result, as follows:
public class Reference implements Serializable {
@Id
@Column(name = "reference_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int referenceID;
@OneToMany(mappedBy = "reference", cascade=CascadeType.ALL)
private Attachment attachment;
@OneToMany(mappedBy = "reference", cascade=CascadeType.ALL)
private Uuid uuid;
MORE STUFF
}
public class Attachment implements Serializable {
@ManyToOne
@JoinColumn(name = "reference_id")
private Reference reference;
MORE STUFF
}
public class Uuid extends Serializable {
@ManyToOne
@JoinColumn(name = "reference_id")
private Reference reference;
MORE STUFF
}
Upvotes: 1
Reputation: 61
What I understand from your code, you shouldn't set cascade property of @ManyToOne annotation for the owning entity's field of the referenced entity. On the contrary, you must set the cascade property of @OneToMany annotation in the parent entity for the child entity field. For example:
class ParentEntity {
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private ChildEntity child;
...
}
class ChildEntity {
@ManyToOne
private ParentEntity parent;
...
}
Upvotes: 1