When a you close an EntityManager, all its managed entities become detached. There is nothing wrong with that. You can still work with the detached entities as java objects, but changing their properties will not affect the database (unless you reattach it). Also once an entity is detached, you can no longer follow lazy-loaded relationships that have not been initialized while the entity was still attached.
You can later reattach a detached entity to a different EntityManager by invoking the merge()
method on it. For example:
// Here myEntity is managed by entityManager1.
SomeEntity myEntity = entityManager1.find(SomeEntity.class, id);
// myEntity becomes detached.
entityManager1.close();
// I can still work with the java object.
myEntity.setSomeProperty("blah");
// Here myEntity becomes managed by entityManager2.
// It basically retrieves the current entity from the DB (based on its ID),
// then apply any change that was made to it while it was detached.
myEntity = entityManager2.merge(myEntity);
// If you commit at this point, the changes made to myEntity while
// it was detached will be persisted to the DB.
To prevent a situation where changes are made "behind your back" in the database while an entity is detached (e.g. another application modifies the corresponding row), you can use a @Version field. Each time the entity is modified, its version changes. If you try to merge a detached entity and the current version retrieved from the database has a different version, it will throw a OptimisticLockException
.