2011-03-08 93 views
13

我设置了一个基本的测试数据util并且想要跟踪EntityManager处理的所有数据。有没有一种方法可以一举抓住由EntityManager管理的所有内容?有没有办法从EntityManager获取所有的管理实体

因此,不是这样的:

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); 
} 

我想是这样的;

EntityManager em; 

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

不知道这是否可能,但我只是想像管理员知道它在管理什么?或者,如果您有任何关于轻松管理一堆实体的想法。

回答

20

我想这可能帮助:

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); 
} 

基本上的EntityManager ::元模型包含有关管理的实体的元数据信息。

+3

其他任何人通过:变量名“className”误导我一点,因为它实际上是jpaEntityName。要获得实际的类,应该使用getBindableJavaType。 @Faisal,谢谢你指点我在正确的方向 – Ittai 2012-01-11 06:41:47

+3

我不确定这是否做OP的要求。它似乎打印可以从数据库中获取的所有实体,但不是所有由EntityManager管理的实体。 – 2012-11-01 14:05:18

+0

这真是错误!正如@MarcusJuniusBrutus已经指出的那样,这会加载数据库中所有已知实体的所有行。代码完成后,您实际上可以掌握所有加载的实体。但这不是在执行代码之前进行管理的实体。 – BetaRide 2018-01-08 06:32:03

1

如果您需要删除测试期间插入的所有实体,则可以在事务内执行测试,然后回滚该事务。作为这种方法的一个例子,请参见9.3.5.4 Transaction management

4

您使用的是JPA提供程序?

JPA API中没有任何内容。

如果使用的EclipseLink,您可以使用,

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

而对于Hibernate,您可以使用https://stackoverflow.com/questions/16460796/hibernate-how-to-get-a-list-of-all-the-objects-currently-in-the-session – Foumpie 2017-09-11 12:11:48

相关问题