1

有没有办法遍历 Stateful Bean 中所有列出的 EntityManager?

@Stateful
@Local(SomeInterface.class)
public class ContextBean implements SomeInterface{

    @PersistenceContext(unitName="00")
    private EntityManager em00;

    @PersistenceContext(unitName="01")
    private EntityManager em01;

    ...

    @PersistenceContext(unitName="0n")
    private EntityManager em0n;

    public ContextBean() {}

    public void test(){

       for(EntityManager em : ???){
         // Do something
       }

    }

}

我可以使用循环吗?请问如何使用?

4

1 回答 1

2

当然,您可以遍历每个字段,如下所示:

    Field[] fields = getClass().getDeclaredFields();
    for (Field field : fields) {
        if (field.getType().equals(EntityManager.class)) {
            EntityManager em = (EntityManager) field.get(this);
            // do something with em
        }
    }
于 2012-12-18T11:51:19.927 回答