Frage

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;
    }
}
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top