Search |
||
EntityManager.persist() throws TransactionRequiredException in a servlet?Posted by ss141213 on December 5, 2005 at 9:37 AM PST
In my last blog I discussed about using Java Persistence API in a web application. In this article I shall talk about a very common mistake that a web-app developer commits and how to fix it. Java Persistence API is part of Java EE 5 platform which is being reference implemented in open source project called glassfish. Code that does not work: public class RegistrationServlet extends HttpServlet {
// This injects the default persistence unit.
@PersistenceUnit private EntityManagerFactory emf;
public void service (HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
try {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
...
String name = req.getParameter("name");
String password = req.getParameter("password");
UserCredential credential = new UserCredential(name, password);
EntityManager em = emf.getEntityManager(); // container managed em
// em.persist makes the new object as persistent and managed.
em.persist(credential);
out.println("Successfully created the new user. ");
} catch (Exception nse) {
throw new ServletException(nse);
}
}
// other servlet methods like init etc. are omitted for bravity.
}
Exception Details: Why this exception occurs? What is the fix? public class RegistrationServlet extends HttpServlet {
// This injects the default persistence unit.
@PersistenceContext private EntityManagerFactory emf;
// This injects a user transaction object.
@Resource private UserTransaction utx;
public void service (HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
try {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
...
String name = req.getParameter("name");
String password = req.getParameter("password");
// we must begin a tx.
utx.begin();
UserCredential credential = new UserCredential(name, password);
EntityManager em = emf.getEntityManager(); // container managed em
// em.persist makes the new object as persistent and managed.
em.persist(credential);
// commit the transaction,
// b'cos web container rollbacks unfinished tx at the end of request
utx.commit();
out.println("Successfully created the new user. ");
} catch (Exception nse) {
throw new ServletException(nse);
}
}
// other servlet methods like init etc. are omitted for bravity.
}
Comparison with equivalent code in a Session Bean @Stateless
class PasswordManagerBean implements PasswordManager {
@PersistenceContext private EntityManager em;
public void createNewUser(String name, String password) {
UserCredential credential = new UserCredential(name, password);
// em.persist makes the new object as persistent and managed.
em.persist(credential);
}
}
Let's analyse the differences between ejb and servlet code: »
Related Topics >>
J2EE Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|