persistence@glassfish.java.net

Is this pattern safe to use in a web app?

From: Jon Miller <jemiller_at_uchicago.edu>
Date: Sun, 14 Jan 2007 02:26:10 -0600

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();
        }
    }
}