Need help understanding JPA and detached entities.
586463May 6 2008 — edited May 6 2008I keep getting the dreaded "Cannot Persist detached object" and I cannot understand why EclipseLink is even trying to persist the object.
The following is a general scenerio if the issue:
1. I have 3 objects "Parent", "Child", and "Agency".
2. I create a new "Agency" and persist it using em.persist(agency).
3. The "Parent" object contains a OneToMany relation to "Child" and "Child" has a reference to "Agency".
4. So I do something like:
agency = new Agency();
em.persist(agency);
child = new Child();
child.setAgency(agency);
parent = new Parent();
parent.addChild(child);
em.persist(parent);
I have Cascade.ALL on the OneToMany relation so I expect that persisting the parent will also persist the child. This part works, however for some reason the agency is trying to be saved and that's were I get the error.
Now if agency was not already persisted, everything works fine. Parent, Child, and Agency all get persisted.
Since there isn't really a way to merge() agency how do I handle this issue?
I don't really understand all the clones and how merge works, so I don't have a good grasp on how cascade works itself through the objects? I did step through the code in the debugger and it simply wants to register agency as a new object even though the primary key is set.