views:

748

answers:

1

(How) is it possible to persist a JPA Entity at the databases of multiple servers without copying everything to DTOs?

We have a distributed system. Some applications do have DBs for caching purposes. The JPA Provider throws an Exception in which it complains that it cannot persist a detached object.

But I would like to preserve the ID of the entity with just persisting it in this additional DB.

(JPA 1.2, EJB 3.0, Glassfish v2.1, Toplink Essentials)

+1  A: 

Don't em.persist(obj), just em.merge(obj). Merge works with both attached and detached objects.

If you are starting with a detached object, I would merge the object with the respective EntityManagers. If you're trying to keep the identity key the same across the objects, I would pull the key from the first object merged, and use it in the future.

What you probably (I don't know) don't want to do is try and merge an object that is managed by one EM with another EM. You can test this to see if it works, I just don't know what will happen if you try.

So.

YourEntity unattachedEntity = ... // your original entity object.

YourEntity managedEntity = em1.merge(unattachedEntity);

// managedEntity now has the primary key assigned by the DB
unattacheEntity.setPrimaryKey(managedEntity.getPrimaryKey());

em2.merge(unattachedEntity);
em3.merge(unattachedEntity);

Something like that should work ok.

Will Hartung
Thank you so much! It really just worked! Your answer was incredibly helpful! I did try merge before - but not with your magic trick using the two entities.
SAL9000