Reputation: 47
I have two tables: Accounts
and Mails
.
1 user from Accounts can have some mails (1 : M ratationship).
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.
Upvotes: 1
Views: 5772
Reputation: 96
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.
Upvotes: 1