Wednesday 14 December 2011

JPA: DO NOT PUT CascadeType in both parts of a two class-relationship (1-1,m-n,n-m,whatever)!!!

JPA: DO NOT PUT CascadeType in both parts of a two class-relationship (1-1,m-n,n-m,whatever)!!! Assume a Boy who has many Toys (1-n relationship). Boy.java
@OneToMany(targetEntity=Toy.class, mappedBy="Toy", fetch=FetchType.EAGER)//CascadeType here?
public Set getToys() {
 return toys;
}
Toy.java
@ManyToOne//CascadeType here?
@JoinColumn(name="BOY_ID")
public Boy getBoy() {
 return boy;
}
Where should I put the Cascade? In Boy or in Toy?Or in both? ANSWER: only in one of them. If you put it in both then one will override the other!!

Example #1 (wrong: overriding cascade)

cascade=CascadeType.ALL in Boy:getToys()
cascade={CascadeType.PERSIST,CascadeType.MERGE} in Toy::getBoy()
// throws exception "Deleted entity passed to persist"
entityManager.deleteById(toy.getId());

Example #2 (right)

cascade={CascadeType.PERSIST,CascadeType.MERGE} only in Toy::getUser()
//works fine :)
entityManager.deleteById(toy.getId());

No comments:

Post a Comment