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

问题描述 投票:0回答:2

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

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类,所以我尝试了以下但我得到了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容器

jpa ejb cdi
2个回答
2
投票

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

@ApplicationScoped
class EntityManagerProducer {

   @PersistenceContext(...)
   private EntityManager em;

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

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

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

如果您有多个持久性上下文,则为每个持久性上下文实现一个生成器方法,并使用CDI-Qualifier对它们进行限定。


-2
投票

我这样解决了:

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);
    }
    ...
© www.soinside.com 2019 - 2024. All rights reserved.