How to use EntityManager API in web module

The javax.persistence.Entitymanager API is used for creating, finding and updating entity bean instances. I would like to show how EntityManager can be used in web module. I will focus only to Glassfish implementation. I know that Oracle App server uses a little bit different approach. They use EntityManager that is bind to java:comp/ejb/<module-name>/EntityManager.
First, some actions with EntityManager API are required to be used in a transaction, so the web module must manually demarcate the transaction using the UserTransaction API.
In objects that are managed by container like servlets, JSF beans and EJB bean you can use simple injection. Following sample explains how to use EntityManager in servlet:
     @PersistenceContext
     EntityManager em;
     @Resource
     UserTransaction tx;
     ....
     tx.begin();
     em.persist(new YourObject());
     tx.commit();
   
This approach can't be used in helper or business delegate classes. There, we should lookup theEntityManager and the UserTransaction using the JNDI binding:
    InitialContext ctx = new InitialContext();
    UserTransaction tx = (UserTransaction)ctx.lookup("UserTransaction");
    EntityManager em = em = (EntityManager) ctx.lookup("java:comp/env/persistence/EntityManager");
     tx.begin();
     YourObject o1 = em.merge(yourObject); // merge object to the new context
     em.remove(o1);
     tx.commit();
 
You'll need to define a persistence-context-ref for the component environment in which your class will run. It means add these elements in your web.xml file in web-app element:
  <persistence-context-ref>
  <persistence-context-ref-name>persistence/EntityManager</persistence-context-ref-name>
     <persistence-unit-name>unitName</persistence-unit-name>
  </persistence-context-ref>
 
Comments:

Check out http://weblogs.java.net/blog/ss141213/archive/2005/12/dont_use_persis.html I don't think EntityManager should be injected to a web app.

Posted by Sahoo on December 20, 2005 at 10:54 PM CET #

Post a Comment:
Comments are closed for this entry.
About

pblaha

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks