persistence@glassfish.java.net

RE: Is this pattern safe to use in a web app?

From: Gordon Yorke <gordon.yorke_at_oracle.com>
Date: Tue, 16 Jan 2007 14:39:55 -0500

Hello Jon,
    Repeatedly re-creating an EntityManagerFactory would require more cpu cycles then having a single EntityManagerFactory. In TopLink an EntityManagerFactory is currently a wrapper around a singleton but this is not maindated by the specification and each Persistence Provider will implement this differently. I would recommend that you close the old EntityManagerFactory on undeploy as you may be left with artifacts (like mappings) from the original deployment.
--Gordon

-----Original Message-----
From: Jon Miller [mailto:jemiller_at_uchicago.edu]
Sent: Sunday, January 14, 2007 3:26 AM
To: Glassfish Persistence List
Subject: Is this pattern safe to use in a web app?


Hi all,

NetBeans 5.5 has a menu item labelled "Use EntityManager" which generates
code like the following. What I'm wondering is if you had several classes
that had the EntityManagerFactory stored in a private static field like
that, if it would wasting a lot of resources? Or, is it basically a
singleton for a given persistence unit behind the scenes anyway? Also, I
know at least for Hibernate when you create a SessionFactory, it's slow
because it has to parse the config files and what not. Is the same thing
true for TopLink? i.e. is it slow everytime you create a
EntityManagerFactory, or, only the first time? Also, if I don't close the
EntityManagerFactory when a web app is hot redeployed, would that cause a
memory leak? Tomcat seems to leak memory like a sive in general on webapp
redeploys, but, I don't want to exacerbate things. I should say that at the
moment, I'm just using Tomcat in standalone mode and not using an app
server.

Jon

package toplinktest;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Test {

    private static EntityManagerFactory emf =
Persistence.createEntityManagerFactory("ToplinkTestPU");
    public Test() {
    }

    public void test() {

    }

    public void persist(Object object) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            // TODO:
            // em.persist(object); em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
}