Eugene Mironenko
Eugene Mironenko

Reputation: 35

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

I have 2 tables.

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

// Mails
@ManyToOne(cascade=CascadeType.ALL)
@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 CascadeType.DELETE_ORPHAN for the Accounts table, but with that I can't delete parent rows if a child row exists.

Upvotes: 3

Views: 22285

Answers (3)

srikanth yaradla
srikanth yaradla

Reputation: 1235

You are using cascade=CascadeType.ALL in both entities. Try using that only at parent. This should work

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

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

Upvotes: 3

samlewis
samlewis

Reputation: 4048

The "mappedBy" property indicates that the other side owns the relationship, so in your case Mails owns the relationship which is probably not what you want.

JPA Cascades only work in one direction, from the owner of the relationship.

So if you want Mails to be deleted when deleting an Account, you need to switch the owner of the relationship:

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

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

Upvotes: 0

marekful
marekful

Reputation: 15351

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.

Upvotes: 5

Related Questions