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.
I tried another example, which I select data from DB. The "select"-getCategory() works good. But I have no idea that why insert-insertData() does not work.
The error information is:
HTTP Status 500
description: The server encountered an internal error () that prevented it from fulfilling this request.
exception: javax.ejb.EJBException
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.
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.
Here is the bean class
@Stateless
@LocalBean
public class testSession {
public testSession() {
// TODO Auto-generated constructor stub
}
//get all the rows from the category table
public List<Category> getCategory(){
EntityManagerFactory emf;
EntityManager em;
emf=Persistence.createEntityManagerFactory("test");
em=emf.createEntityManager();
String queryStr="select cat from Category cat";
Query query;
query=em.createQuery(queryStr);
List<Category> cat=query.getResultList();
return cat;
}
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();
}
}
In the
servlet
@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("<html><body>");
//call the method in the session bean to insert data
ts.insertData();
out.print("</body></html>");
}
}