What is the correct way of accessing a Java Persistence unit from the web tier (no EJB session beans)?
I use JBoss 4.2.0.
I can't get the resource injection annotations @PersistenceUnit or @PersistenceContext to work, so I have done like this:
public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { try { EntityManagerFactory emf = Persistence.createEntityManagerFactory("myunit"); sce.getServletContext().setAttribute(EntityManagerFactory.class.getName(), emf); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } public void contextDestroyed(ServletContextEvent sce) { EntityManagerFactory emf = (EntityManagerFactory)sce.getServletContext().getAttribute( EntityManagerFactory.class.getName()); if (emf != null) { emf.close(); } } }
EntityManagerFactory emf = (EntityManagerFactory)context.getAttribute(EntityManagerFactory.class.getName()); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); try { // process the request here... transaction.commit(); } catch (Exception e) { transaction.rollback(); // log the error } finally { em.close(); }