Search code examples
jpaeclipselinkentitymanager

How to find all managed attached objects in EntityManager (JPA)


Is there a way to get all objects which are currently attached in the entity manager?
I want to write some monitoring code which will report the number of attached objects and their classes.
Meaning finding all objects which were loaded by previous queries and find operations into the entity manager.
I'm using EclipseLink, so a specific solution is good too.


Solution

  • EclipseLink's JPA interface pretty much wraps its native code such that an EntityManager uses a UnitOfWork session underneath (and the EMF wraps a ServerSession). You need to get at the UnitOfWork if you want to see what entities it is managing.

    If using JPA 2.0, you can use the EntityManager unwrap method:

    UnitOfWork uow = em.unwrap(UnitOfWork.class);
    

    otherwise, use some casting

    UnitOfWork uow = ((EntityManagerImpl)em).getUnitOfWork();
    

    From there, the UnitOfWork has a list of all registered (aka managed) entities. You can use the UOW to directly log what it has using the printRegisteredObjects() method, or obtain it yourself using getCloneMapping().keySet().

    You can also see deleted objects by using hasDeletedObjects() and then getDeletedObjects().keySet() if there are any, as and the same for new objects using hasNewObjectsInParentOriginalToClone() and getNewObjectsCloneToOriginal().keySet()