相关疑难解决方法(0)

如何在一个很好地解耦的服务层和数据访问层中使用EntityManager?

与我的另一个问题有点相关应该从数据访问层或接口返回原始的Hibernate注释POJO吗?,我在创建很好的分离层方面很有经验,但没有使用Hibernate或J2EE/JPA.我一直在查看文档和教程,并对如何以优雅的方式使用EntityManger感到困惑,因为它似乎负责两个事务(我想在我的服务层执行)和持久性方法(我想要的)保持在数据访问层).我应该在服务层创建它并将其注入数据访问层,还是有更好的方法?下面的伪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 
    }

}
Run Code Online (Sandbox Code Playgroud)

hibernate jpa data-access-layer entitymanager service-layer

10
推荐指数
1
解决办法
6072
查看次数