Question

Is there a better way/place of getting/instanting a EntityManagerFactory in a web service (METRO 2.0) on a Tomcat server than in a static initializer of a web service itself?

@WebService
public class TestWebService {

    private static EntityManagerFactory entityManagerFactory;

    static
    {
        entityManagerFactory = Persistence.createEntityManagerFactory("TestWSPU");
    }

    @WebMethod
    public List<User> getUsers() {
        EntityManager em = entityManagerFactory.createEntityManager();

        List<User> users = em.createQuery("from User u", User.class).getResultList();

        em.close();

        return users;
    }
}
Était-ce utile?

La solution

If you're using plain Tomcat (e.g., not TomEE), you could use a ServletContextListener to create the EMF, and then put it into a singleton. Then from that singleton maybe expose a method to give you an EntityManager.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top