Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get all managed entities from an EntityManager

I'm setting up a basic test data util and want to keep track of all the data that the EntityManager handles. Rather than just having a bunch of lists for each entity is there a way to grab everything being managed by the EntityManager in one fell swoop?

So instead of this:

EntityManager em;
List<Entity1> a;
List<Entity2> b;
...
List<Entityn> n;

cleanup() {
    for(Entity1 e : a) em.remove(e);
    for(Entity2 f : b) em.remove(f);
    ...
    for(Entityn z : n) em.remove(z);
}

I want something like this;

EntityManager em;

cleanup() {
    List<Object> allEntities = em.getAllManagedEntities(); //<-this doesnt exist
    for(Object o : allEntities) em.remove(o);
}

Not sure if this is possible, but I just would image that the manager knows what it is managing? Or, if you have any ideas of managing a bunch of entities easily.

like image 300
Th3sandm4n Avatar asked Mar 08 '11 06:03

Th3sandm4n


People also ask

What is difference between EntityManagerFactory and EntityManager?

EntityManagerFactory vs EntityManagerWhile EntityManagerFactory instances are thread-safe, EntityManager instances are not. The injected JPA EntityManager behave just like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification.

What does EntityManager find do?

The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit.


1 Answers

I think this might help:

for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
    final String className = entity.getName();
    log.debug("Trying select * from: " + className);
    Query q = entityManager.createQuery("from " + className + " c");
    q.getResultList().iterator();
    log.debug("ok: " + className);
}

Basically EntityManager::MetaModel contains the MetaData information regarding the Entities managed.

like image 100
Faisal Feroz Avatar answered Oct 10 '22 21:10

Faisal Feroz