与我之前的问题有些相关 (Hibernate注释的POJO应该从数据访问层返回,还是应该使用接口?) ,我擅长创建漂亮的解耦层,但不使用Hibernate或J2EE/JPA。我一直在查找文档和教程,对如何优雅地使用EntityManager感到困惑,因为它似乎负责事务(我希望在服务层中执行)和持久化方法(我希望保留在数据访问层中)。我应该在服务层创建它并将其注入到数据访问层中,还是有更好的方法?下面的伪java代码大致展示了我的想法。
编辑:我的下面的伪代码基本上是从Hibernate JPA教程中摘取的,并针对分层进行了修改,不反映正在开发的产品要在EJB容器(Glassfish)中运行。请在您的答案中给出在Glassfish或等效环境中运行的最佳实践和代码示例。
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
}
}