Is it safe to do something like this with CDI?
@Named
@ApplicationScoped
public class DAO {
@PersistenceContext
private EntityManager entityManager;
}
>
What about this approach:
@RequestScoped class EntityManagerProducer { @PersistenceContext private EntityManager entityManager; @Produces @RequestScoped public EntityManager produceEntityManager() { return this.entityManager; } }
And in CDI Beans of any scope:
@Inject private EntityManager entityManager;
The entity manager should be created in every single request, creating a new entity manager when it passes one CDI bean which it injects. In the injected CDI Bean, you get one entity manager which is used within the request. If a transaction is needed, the entity manager will join it. So you get a new entity manager in every request which means, everything is cleaned up at the end and you cannot get thread conflicts. Simple and easy, isn't it?