0
votes

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?

2

2 Answers

0
votes

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.

0
votes

Making a class an EJB will give the class some features that EJB has and Container manages, such as Transaction Management, Thread Safety, Security and so on.

In Ejb in Action book, it is said that it is recommended to have a simple DAO class (Not an EJB) which works with EntityManager. DAO classes should not being involved in Transaction Management and other features that EJB has, instead, there should always be an EJB that uses DAO class (Using @Inject annotation) and other services such as REST or SOAP web services should call that EJB which use the DAO that we need.

Converting all classes like DAO classes and Utility classes to EJB, will put a burden on container's shoulder and will make it more difficult to manage all EJBs.