Search code examples
mergeassociationsopenjpapersist

openjpa: A new entity with an association to a detached object


I have two objects. Arrangement and InvolvedParty. There is an association between Arrangement and InvolvedParty.

When I create my first Arrangement and attach the InvolvedParty to it there is no problem during the persist. When I create my second Arrangement and fetch the previously stored InvolvedParty from the database to attach it to the second Arrangement the persist will not work.

This is the error: [20/09/12 9:53:40:998 CEST] 00000020 RegisteredSyn E WTRN0074E: Exception caught from before_completion synchronization operation: org.apache.openjpa.persistence.EntityExistsException: Attempt to persist detached object "com.xxx.crs.model.involvedparty.InvolvedParty-com.xxx.crs.model.involvedparty.InvolvedParty-101". If this is a new instance, make sure any versino and/or auto-generated primary key fields are null/default when persisting. FailedObject: com.xxx.crs.model.involvedparty.InvolvedParty-com.xxx.crs.model.involvedparty.InvolvedParty-101

Now what do I have to do? Arrangement is a new object, so considering that I should persist it. But an item of Arrangement is InvolvedParty, which is a detached object so I should do a merge? It feels like a contradiction though.


Solution

  • Make sure that you fetch the existing InvolvedParty from the database in the same transaction that you use to persist the Arrangement. If you do these operations in two separate operations, the persistence context ends when the first transaction completes and OpenJPA will treat the InvolvedParty as a detached object.

    For more information, see Persistence Context from the OpenJPA manual.