persistence@glassfish.java.net

re: Use same persistence unit in ejb and web tier

From: Ian Evans <Ian.Evans_at_Sun.COM>
Date: Tue, 24 Oct 2006 10:58:54 -0700

Benjamin Graf <Benjamin.Graf_at_gmx.net> wrote:
> one problem is still there. How can I access this global defined
> persistence unit. I tried an lookup,
>
> Context ctx = new InitialContext();
> em = (EntityManager)
> ctx.lookup("java:comp/env/persistence/LogicalName");
> persistence/LogicalName registered in web.xml
>
> but the EntityManager was null.

In a web application that can't do resource injection, you use an
EntityManagerFactory to create entity managers. You can't look up entity
managers through JNDI.

EntityManagerFactory emf =
Persistence.createEntityManagerFactory("PersistenceUnitName");
EntityManager em = emf.createEntityManager();

If your web app is a servlet or has a JSF backing bean, you can inject
the persistence unit just as you would in a session bean.

I suggest you read the "Persistence in the Web Tier" chapter and look at
the bookstore examples in the Java EE Tutorial. They demonstrate
different strategies in web apps. For example, bookstore2 uses a servlet
context listener to inject the entity manager factory.

-i
-- 
Ian Evans
ian dot evans at sun dot com
Java EE technical documentation