Wednesday December 14, 2005
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>
Posted by pblaha
( Dec 14 2005, 05:47:22 PM CET )
Permalink
Comments [1]