简体   繁体   中英

How to realize ON UPDATE CASCADE and ON DELETE CASCADE in Hibernate(JPA)?

I have two tables: Accounts and Mails .

1 user from Accounts can have some mails ( 1 : M ratationship ).

  • When user is deleting his profile (from Accounts ), hibernate should delete all mails for that user (from Mails ). Accounts has id (PK) and other columns. Mails has id(PK), user_id(FK: user_id -> Accounts.id) and other columns.

How to achieve above kind of implementation on Hibernate (or JPA)?

My entity classes are as follows:

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

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

But when I'm editing or deleting some parent rows, hibernate says: Cannot delete or update a parent row: a foreign key constraint fails. So exactly where am I making ​​a mistake?


UPDATE

This error occurs when we execute SQL or HQL queries and it's not true. We should use entitymanager.remove or entitymanager.merge methods. My entity classes are valid.

it seems you have a bi-directional relation between account and mails. In the account class you have to use somethink like:

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

Property mappedby is required for bi-directional. Hint: In my opinion you should only use bi-directional relations if it is really necessary.

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