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)?
You can use the @PersistenceContext annotation to inject an EntityManager in an EJB 3.0 client (such as a stateful or stateless session bean, message-driven bean, or servlet). You can use @PersistenceContext attribute unitName to specify a persistence unit by name, as Example 29-13 shows.
The persist method is intended to add a new entity instance to the persistence context, i.e. transitioning an instance from a transient to persistent state. We usually call it when we want to add a record to the database (persist an entity instance): Person person = new Person(); person.
An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With