简体   繁体   中英

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.

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 .

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM