本文介绍了获取EntityManagerFactory的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best approach to get EntityManagerFactory in web app(jsp/servlets)?Is this a good way When should EntityManagerFactory instance be created/opened?,or is it better to get it from JNDI, or something else?

推荐答案

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

They're heavyweight and they're supposed to be in the application scope. So, you need to open them on application startup and close them on application shutdown.

如何执行此操作取决于您的目标容器。它是否支持EJB 3.x(Glassfish,JBoss AS等)?如果是这样的话,那么如果只是在带有通常的方式:

How to do that depends on your target container. Does it support EJB 3.x (Glassfish, JBoss AS, etc)? If so, then you don't need to worry about opening/closing them (neither about transactions) at all if you just do the JPA job in EJBs with @PersistenceContext the usual way:

@Stateless
public class FooService {

    @PersistenceContext
    private EntityManager em;

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

    // ...
}

如果目标容器不支持EJB(例如Tomcat,Jetty等)和EJB加载项,如。这是基本启动示例:

If your target container doesn't support EJBs (e.g. Tomcat, Jetty, etc) and an EJB add-on like OpenEJB is also not an option for some reason, and you're thus manually fiddling with creating EntityManagers (and transactions) yourself, then your best bet is a ServletContextListener. Here's a basic kickoff example:

@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,此类需要在 web.xml 中由< listener> 注册,而不是)

(note: before Servlet 3.0, this class needs to be registered by <listener> in web.xml instead of @WebListener)

可以用作:

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

这篇关于获取EntityManagerFactory的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 22:11