Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of managed Entity instances in a persistence context

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

like image 797
Boris B. Avatar asked Dec 15 '13 16:12

Boris B.


People also ask

What is @PersistenceContext annotation used for?

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.

Which method in JPA adds an entity to the persistence context?

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.

What is EntityManager and persistence context?

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.


1 Answers

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

like image 148
Steve Ebersole Avatar answered Oct 13 '22 16:10

Steve Ebersole