Using Entities in Java EE Applications
  • EntityManagers are obtained via "Dependency Injection"
  • Within the context of an EJB method, the JTA transaction will be started for you
EJB Example  
  • In a servlet environment, you must initiate the JTA transactions yourself (a servlet filter maybe)
Servlet Example  
  public class EmployeeListServlet extends HttpServlet {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    UserTransaction utx;

    protected void doGet(HttpServletRequest req,
                          HttpServletResponse res) {
      try {
        utx.begin();
        Query query = entityManager.createQuery( "select x from Employee x" );
        req.setAttribute( "employees", query.getResultList() );
        req.getRequestDispatcher("/employeeList.jsp" ).forward( req, res );
        utx.commit();
      } catch( Exception e ) {
        try {
          utx.rollback();
        } catch (Exception ee) {
          // Log exception!
        }
        throw new ServletException(e);
      }
    }
  }