rubaka
rubaka

Reputation: 47

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).

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

Answers (1)

Caron
Caron

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

Related Questions