title: use session bean to insert data with JPA
body: <p>In a servelt, I try to call the session bean method to insert data to database via JPA. The insert process is written in the session bean. </p>
  
  <p>I tried another example, which I select data from DB. The "select" works good. But I have no idea that why insert does not work.</p>
  
  <p>The error information is:</p>
  
  <p>HTTP Status 500</p>
  
  <p>description: The server encountered an internal error () that prevented it from fulfilling this request.</p>
  
  <p>exception: javax.ejb.EJBException</p>
  
  <p>note: The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.0.1 logs.</p>
  
  <p>I think there is something wrong with "tx.commit()", when I comment it then there is no error. But I do not know what the exactly problem.</p>
  
  <p>Here is the bean class</p>
  
  <pre><code>@Stateless
  @LocalBean
  public class testSession {
  
    public testSession() {
      // TODO Auto-generated constructor stub
    }
  
    public void insertData(){
      EntityManagerFactory emf;
      EntityManager em;
  
      //the Entity Class-Category
      Category cat=new Category();
  
      //set value
      cat.setId(5);
      cat.setName("test cat");
  
      //the "test" is the persist unit in persistence.xml 
      emf=Persistence.createEntityManagerFactory("test");
      em=emf.createEntityManager();
  
      EntityTransaction tx=em.getTransaction();
      tx.begin();
      em.persist(cat);
      tx.commit();
      em.close();
      emf.close();
  
    }
  }
  </code></pre>
  
  <p>In the servlet</p>
  
  <pre><code>@WebServlet("/testServlet")
  public class testServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  
  @EJB
  testSession ts;
  
  public testServlet() {
     super();
  }
  
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      PrintWriter out=response.getWriter();
      out.print("&lt;html&gt;&lt;body&gt;");
      //call the method in the session bean to insert data
      ts.insertData();
      out.print("&lt;/body&gt;&lt;/html&gt;");
  }
  
  
  }
  </code></pre>