Java – how to delete all child rows when deleting a parent using Hibernate?

I have two 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 to delete all child rows when deleting a parent row? I tried to set the cascadetype for the accounts table DELETE_ Orphan, but if there are child rows, I cannot delete the parent row

Solution

The problem may be that the relationship is defined in the wrong direction Suppose you have an account table with a one to many relationship with the mail table. If you define the account relationship as referring to mail, you will not be able to delete records from the account until it has associated mail behavior The correct method is to create a foreign key on the mail to reference account

Using on delete cascade, you tell MySQL that it should delete a row whose table has a foreign key if its parent (referenced by the key) is deleted The definition allows this operation because in this case the deleted record has a reference to it Conversely, if a record has references to other records in it, deletion is not allowed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>