获取EntityManagerFactory的最佳实践

时间:2011-10-22 21:23:47

标签: java jpa jndi

在Web应用程序(jsp / servlets)中获取EntityManagerFactory的最佳方法是什么? 这是一个好方法When should EntityManagerFactory instance be created/opened?, 或者从JNDI或其他什么地方获得它更好?

1 个答案:

答案 0 :(得分:61)

他们是重量级的,他们应该在应用范围内。因此,您需要在应用程序启动时打开它们,并在应用程序关闭时关闭它们。

如何做到这一点取决于您的目标容器。它是否支持EJB 3.x(Glassfish,JBoss AS等)?如果是这样的话,那么如果你只是以@PersistenceContext通常的方式在EJB中执行JPA作业,那么你根本不需要担心打开/关闭它们(对于事务都没有):

@Stateless
public class FooService {

    @PersistenceContext
    private EntityManager em;

    public Foo find(Long id) {
        return em.find(Foo.class, id);
    }

    // ...
}

如果您的目标容器不支持EJB(例如Tomcat,Jetty等),并且像OpenEJB这样的EJB加载项由于某种原因也不是一个选项,那么您就可以手动摆弄创建EntityManager s(和交易)自己,那么你最好的选择是ServletContextListener。这是一个基本的启动示例:

@WebListener
public class EMF implements ServletContextListener {

    private static EntityManagerFactory emf;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        emf = Persistence.createEntityManagerFactory("unitname");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        emf.close();
    }

    public static EntityManager createEntityManager() {
        if (emf == null) {
            throw new IllegalStateException("Context is not initialized yet.");
        }

        return emf.createEntityManager();
    }

}

(注意:在Servlet 3.0之前,此类需要<listener>中的web.xml而不是@WebListener注册

可以用作:

EntityManager em = EMF.createEntityManager();
// ...