Search code examples
javahibernatejpaejbejb-3.1

How to pass entity manager injected in statelesbean to dao without setter method


I am working on a project where I have separated EJB such that they only carry out the business logic but not performing the queries. Then I also have the DAOs that performs the queries. For me to use the DAOs, I inject the DAOs in the EJB and with a method annotated @PostConstruct, I set the EntityManager in the DAO with the EntityManager injected in the bean like bellow:

public class ClazzDao implements ClazzDaoI{

  private EntityManager em;

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

  public List<Entity> list(){
      return em.createQuery("FROM Entity e").getResultList();
  }

}

And the EJB

@Stateless    
public class ClazzBean implements ClazzBeanI{
  @PersistenceContext
  private EntityManager em;

  @Inject
  private ClazzDaoI clazzDao;

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

  public BigDecimal sendEmailToMembers(){

     List<Entity> members = clazzDao.list();
     //do some stuff with data like say send emails...

  }

}

Is there a way that I can make the DAOs use the entity manager injected in the EJB without setting it at the @PostConstruct of the EJB?


Solution

  • You can use inject capability only in container managed beans. You dao class is outside of container management no way to inject the EntityManager into this object. Put you class into container management (EJB/CDI) if you need injection capability. By the way avoid to use unnecessary interfaces use non interface view instead.