Why won't JPA delete owned entities when the owner entity loses the reference to them?
- by Nick
Hi!
I've got a JPA entity "Request", that owns a List of Answers (also JPA entities). Here's how it's defined in Request.java:
@OneToMany(cascade= CascadeType.ALL, mappedBy="request")
private List<Answer> answerList;
And in Answer.java:
@JoinColumn(name = "request", referencedColumnName="id")
@ManyToOne(optional = false)
private Request request;
In the course of program execution, the Request's List of Answers may have Answers added or removed from it, or the actual List object may be replaced. My problem is thus: when I merge a Request to the database, the Answer objects that used to be in the List are kept in the database -- that is, Answer objects that the Request no longer holds a reference to (indirectly, via a List) are not deleted.
This is not the behaviour I desire, as if I merge a Request to the database, and then fetch it again, its Answers List may not be the same. Am I making some programming mistake? Is there an annotaion or setting that will ensure that the Answers in the database are exactly the Answers in the Request's List?
A solution is to keep references to the original Answers List and then use the EntityManager to remove each old Answer before merging the Request, but it seems like there should be a cleaner way.
Thank you!