Th3sandm4n
Th3sandm4n

Reputation: 809

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.

Upvotes: 21

Views: 25453

Answers (3)

Faisal Feroz
Faisal Feroz

Reputation: 12785

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.

Upvotes: 25

James
James

Reputation: 18379

What JPA provider are you using?

There is nothing in the JPA API for this.

If using EclipseLink, you can use,

em.unwrap(UnitOfWorkImpl.class).getCloneMapping().keySet()

Upvotes: 3

axtavt
axtavt

Reputation: 242686

If you need to remove all entities inserted during a test, you can execute the test inside a transaction and then rollback that transaction. See 9.3.5.4 Transaction management as an example of this approach.

Upvotes: 1

Related Questions