21

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.

Th3sandm4n
  • 809
  • 4
  • 13
  • 23

3 Answers3

25

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.

Faisal Feroz
  • 12,458
  • 4
  • 40
  • 51
  • 3
    For anyone else passing by: The variable name "className" mislead me a bit as it is actually the jpaEntityName. To get the actual class one should use getBindableJavaType. @Faisal, thanks for pointing me in the right direction – Ittai Jan 11 '12 at 06:41
  • 8
    I am not sure that does what the OP asked for. It seems to print all entities that can be fetched from the database, but not all entities that are *currently* managed by the EntityManager. – Marcus Junius Brutus Nov 01 '12 at 14:05
  • 1
    This is just plain wrong! As @MarcusJuniusBrutus is already pointing out, this loads all rows of all known entities from the DB. When the code finishes you can actually get a hand on all loaded entities. But this are not the entities which where managed before executing the code. – BetaRide Jan 08 '18 at 06:32
3

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()
James
  • 17,965
  • 11
  • 91
  • 146
  • 1
    And for Hibernate you can use https://stackoverflow.com/questions/16460796/hibernate-how-to-get-a-list-of-all-the-objects-currently-in-the-session – Foumpie Sep 11 '17 at 12:11
1

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482