是否可以通过多个 bean 将 EntityManager 作为参数传递?

Is it possible to pass EntityManager as a parameter through multiple beans?

我知道我可以做到以下几点:

public class MyDao{

  private EntityManager em;

  public void setEm(EntityManager em){
     this.em = em;
  }
  ...

然后,使用 @PostConstuct 传递 EntityManager

public class MyBean{
  private EntityManager em;

  @Inject
  private MyDao myDao;

  @PostConstruct
  private void init(){
    myDao.setEm(em);
  }
...

但是由于我的应用程序的体系结构限制,我不能直接将 MyDao 注入 MyBean,我应该通过 MyBusinessDao Class,所以我尝试了以下但我得到的值是 nullPointerExeception MyDao 中的 EntityManager 个:

    public class MyBean{

    private EntityManager em;

    public MyBean(){
        em = createEntityManager();
    }

    private EntityManager createEntityManager(){
        //dynamically create the EntityManager
    }

    @Inject
    private MyBusinessDao myBusinessDao;

    @PostConstruct
    private void init(){
       myBusinessDao.setEm(em);
    }
   ...

并在 MyBusinessDao 中注入 MyDao:

 public class MyBusinessDao {

    private EntityManager em;

    @Inject
    private MyDao myDao;

    @PostConstruct
    private void init(){
      myDao.setEm(em);
    }
    ...

我应该提一下,我没有使用 J2EE 容器

我是这样解决的:

public class MyBusinessDao {

    private EntityManager em;

    @Inject
    private MyDao myDao;

    private void setEm(EntityManager em){
    this.em = em;
    //and here i call the setEm method of myDao also
    myDao.setEm(em);
    }
    ...

您可以实现 CDI 生产者方法以通过 CDI 注入提供 EntityManager。

@ApplicationScoped
class EntityManagerProducer {

   @PersistenceContext(...)
   private EntityManager em;

   @Produces
   @RequestScoped
   public EntityManager produceEm() {
      return em;
   }
}

您还可以在生产者方法中注入 EntityManagerFactory 并调用 emf.createEntityManager() 并实现 CDI-Disposer 方法,该方法会在范围完成之前关闭 EntityManager。

public void dispose(@Disposes EntityManager em) { ... }

如果您有多个持久化上下文,则为每个持久化上下文实现一个生产者方法,并使用 CDI 限定符对其进行限定。