I have a JPA-persisted object model that contains a many-to-one relationship: an Account has many Transactions. A Transaction has one
Since this is a very common question, I wrote this article, on which this answer is based on.
In order to fix the problem you need to follow these steps:
So, you need to remove the @CascadeType.ALL from the @ManyToOne association. Child entities should not cascade to parent associations. Only parent entities should cascade to child entities.
@ManyToOne(fetch= FetchType.LAZY)
Notice that I set the fetch attribute to FetchType.LAZY because eager fetching is very bad for performance.
Whenever you have a bidirectional association, you need to synchronize both sides using addChild and removeChild methods in the parent entity:
public void addTransaction(Transaction transaction) {
transcations.add(transaction);
transaction.setAccount(this);
}
public void removeTransaction(Transaction transaction) {
transcations.remove(transaction);
transaction.setAccount(null);
}
For more details about why it's important to synchronize both ends of a bidirectional association, check out this article.