Entity objects don't have a reference to the session (entityManager) which loaded/created them.
An exception are persistent collections, they have such a reference in order to allow lazy loading.
So if your entity object has persistent collections, you can get the original session by following hack:
Code:
AbstractPersistentCollection collection = (AbstractPersistentCollection ) myentity.getAllChilds();
Session = getSession();
Once you have the session you should be able to map it to the right entityManager.
But anyway this is a hack which I do not recommend.
I prefer another approach, which work also on entities without having any collections inside:
I use a PostLoadListener to memoryze the session (entityManager) like this:
Code:
<property name="hibernate.ejb.event.post-load" value="MyPostLoadListener"/>
Code:
public class MyPostLoadListener extends DefaultPostLoadEventListener {
@Override
public void onPostLoad(PostLoadEvent event) {
super.onPostLoad(event);
if (event.getEntity() != null) {
SessionImpl session = (SessionImpl) event.getSession();
MyPersistentMappedSuperclass= (MyPersistentMappedSuperclass) event.getEntity();
myentity.setSession(session); // holding the session reference in a transient field
}
else throw new HibernateException("Failed postload event! (getEntity() == null)");
}
}