In our application we have to merge a detached entity multiple times. The entity is created and persisted in a business module; and in later stages it is modified and the update is persisted in various business modules. Every business module has a new transaction scope and so the entity becomes detached after the first module where it is persisted. So we are trying to merge the detached entity in every module it is modified. The merge works fine the first time and I understand that the merge returns a new managed entity. But when we try to merge the detached entity again, it throws an OptimisticLockException because the version field of the detached entity is still zero "0". I understand the cause for this problem: When the detached entity is merged for the first time, the version field gets incremented when the transaction commits, but the version value is not reflected in the detached entity. Is there any solution to make this work? Am I doing something wrong?
One workaround I could think of is, have separate update methods for every update, which finds the entity using em.find() method and updates the modified fields using respective setter methods on the returned managed entity. But I feel that is killing the effectiveness of the merge functionality. While using merge, we just don't need to worry about which fields need to be updated, rather just call the merge on it!
I am not really looking for any suggestion to change our business logic. One suggestion could be, why persist the entity first and then keep merging in every module; rather, why not persist the entity at the end after all the updates are done. But this is how our business logic should work - persist the entity in the module which creates it and later do merge on every update.
Is this all happening in one request-response cycle? I'd question why you need so many transactions. Why not create one transaction as the request comes in, hold the session open, and commit when the work is done. That would simplify transaction handling greatly, and improve performance and efficiency.