Eugene Mironenko Eugene Mironenko - 1 year ago 162
SQL Question

How to delete all child rows when parent is deleted using Hibernate?

I have 2 tables.

// Accounts
@OneToMany(mappedBy="accounts", cascade=CascadeType.ALL)
private Set<Mails> mails;

// Mails
@JoinColumn(name="user_id" , referencedColumnName="id", insertable=false, updatable=false)
private Accounts accounts;

How can I organize deleting all child rows when the parent row will be deleted? I have tried to set
for the
table, but with that I can't delete parent rows if a child row exists.


The problem probably is that the relation is defined in the wrong direction. Presuming that you have an account table with one-to-many relation to a mail table, you will end up not being able to delete a record from account until it has associated mail rows if you define the relation on account to reference mail. The correct way is to create the foreign key on mail to reference account.

With ON DELETE CASCADE, you tell MySQL that it should delete a row (whose table has the foreign key) if its parent (referenced by the key) is deleted. This operation is allowed by definition because in such a case the deleted record has references to it. In contrast, a deletion is not allowed if a record has references pointing to other records from it.