Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 481
Avner Levy Avatar asked Oct 18 '25 15:10

Avner Levy


1 Answers

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()

like image 102
Chris Avatar answered Oct 21 '25 13:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!