Search code examples
jpaejb

Should EntityManager be injected into an EJB?


I'm designing a very simple web app with a REST web service that utilizes JPA to interact with a PostgreSQL database and runs in TomEE.

I don't believe I have a need (or desire) to manually manage the lifecycle of the EntityManager therefore I'm planning to offload that chore onto TomEE by using Container Managed EntityManagers (probably Transaction Scoped).

I don't believe I have a need (or desire) to manually manage the JTA Transaction that Container Managed EntityManagers require.

Finally, I plan to use DAO classes to separate any queries from the business logic that is my REST web service.

Is my best option for each DAO class to be an EJB that uses the @PersistenceContext annotation to obtain a reference to an EntityManager? If so, what type of EJB should the DOAs be? I've seen examples/blogs suggesting stateless, stateful, singleton, and even to forget the DAO entirely by injecting the EntityManager into the web services themselves. What is the best way to handle this?


Solution

  • Each DAO should be a Stateless Session Bean where the DB References is Injected.

    Would be nicer to have a GenericDAO to execute CRUD operations through the EntityManager in order to avoid replicating code around the EJB.

    Usually I prefer to create also one EJB for each Ws Client if some service has to be called.

    In case to provide a Ws Server I always inject the EJB instance I need rather than inject the EntityManager instance since it would be a good thing to have a single access point.