Somewhat related to my other question Should raw Hibernate annotated POJO's be returned from the Data Access Layer, or Interfaces instead? , I am experienced in creation of nicely decoupled layers, but not using Hibernate or J2EE/JPA. I have been looking at documentation and tutorials, and am puzzled about how to use the EntityManger in an elegant way, as it seems it is responsible for both transactions (which I want to do at my service layer) and persistance methods (which I want to keep in the data access layer). Should I create it at the service layer and inject it into the data access layer, or is there a better way? The below pseudo-java shows roughly what I'm thinking of doing.
EDIT: My pseudocode below is essentially taken from the hibernate JPA tutorial and modified for the layer separation and does not reflect that the product is being developed to run in an EJB container (Glassfish). In your answers please give best practices and code examples for code running in Glassfish or equivalent.
MyService
{
setup()
{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "Something" ); //is the String you pass in important?
entityManager = entityManagerFactory.createEntityManager();
}
myServiceMethod()
{
entityManager.getTransaction().begin();
MyDao.setEntityManager(entityManagerFactory);
MyDao.doSomething();
MyDao.doSomethingElse();
entityManager.getTransaction().commit();
entityManager.close();
}
}
MyDao
{
doSomething()
{
entityManager.persist(...); //etc
}
}