This is more of an architecture problem that I now have. I need help regarding best practices for integrating EJB and JPA into a project. I want to have EJBs that will run a service layer containing the business logic of my application. Right below that, I would like to have a DAO layer that my EJBs will have a descriptor using the DAO factory to separate the two layers as much as possible. Knowing this, I obviously cannot make my DAO as an EJB either because I don't want them to be entered automatically, since I want them to be created through the factory. This leads me to create the entitymanager manually using
Persistence.createEntityManagerFactory("PortalEJB").createEntityManager();
Now ... this call is in my abstract JPA DAO:
public abstract class JPADataAccessorObject<K, E> implements DataAccessorObject<K, E> { protected Class<E> entityClass; protected EntityManager entityManager; protected JPADataAccessorObject(Class<E> pEntityClass) { this.entityManager = Persistence.createEntityManagerFactory("PortalEJB").createEntityManager(); this.entityClass = pEntityClass; } }
I think this is bad, right? All my specific aspects of this class will have a new copy of the persistence context, and I will get strange behavior. Moreover, when I do this, I think I myself must manage transactions at the service level. I was going to create Aspects for him, something like:
- Creating a transaction before any service level function / procedure
- (transaction rollback if any exception occurs)
- Complete transaction after any service level function / procedure
So here are my questions:
- How do I manage EntityManager?
- Do I have to have some kind of JPA utility class that will manage it so that one protection is protected against multithreading?
- If I make a terrible mistake, please provide the best practices.
source share