9

Is there a way to obtain a list of "known" Entity instances for a given Session/EntityManager in JPA/Hibernate 4.x?

By "known" I mean either loaded, created or changed, i.e. a managed entity that exists in a persistence context. I know of EntityManager#contains method so I'm guessing that such a list is maintained, but how can I get to it?

EDIT: Also, how can I query the state of the persistent entity (check if it is created, updated, deleted or clean in this persistence context)?

Boris B.
  • 4,933
  • 1
  • 28
  • 59

1 Answers1

18

JPA does not define such a capability. But you can do it using Hibernate calls:

final org.hibernate.engine.spi.SessionImplementor session = em.unwrap( org.hibernate.engine.spi.SessionImplementor.class );
final org.hibernate.engine.spi.PersistenceContext pc = session.getPersistenceContext();
final Map.Entry<Object,org.hibernate.engine.spi.EntityEntry>[] entityEntries = pc.reentrantSafeEntityEntries();

entityEntries here is an array of Map.Entry instances whose "key" is the entity itself and whose value is an instance of org.hibernate.engine.spi.EntityEntry that describes various info about the entity, including information like EntityEntry.getStatus().

Steve Ebersole
  • 9,339
  • 2
  • 48
  • 46
  • Thanks for the answer. Btw, do you happen to know what Status.GONE means in hibernate (EntityEntry.getStatus()) ? – Boris B. Dec 16 '13 at 20:15
  • 4
    Status.DELETED indicates that the entity is deleted in regards to the Session/EntityManager. Status.GONE indicates the row has been deleted from the database. – Steve Ebersole Dec 17 '13 at 01:37