Well i understand that EntityManger is not
thread safe and should be avoided in
Servlet's. As when dependency injection is done, it get's saved in instance variable and the same servlet can be invoked by multiple thread's.
So it is better to avoid DI, and use JNDI lookup for EntityManger.
Even if we are doing JNDI lookup, and entityManager get's saved in instance variable. This same variable will be accessed by mutliple thread's.
1) So why JNDI lookup is safe as compared to DI for EntityManger in Servlet's?
this code will not be safe.
2) Does I conclude here that when below class get's loaded, DI is done only 1 time when class is loaded, as multiple thread access this class instance DI will not be done again-2?
--------------
public class RegistrationServlet extends HttpServlet {
// inject default EntityManager
@javax.persistence.PersistenceContext private EntityManager em;
@Resource private UserTransaction utx;
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
...
utx.begin();
em.persist(credential);
utx.commit();
...
}
...
}
----------------------------
3) why this code is safe, when the class get's loaded, for the multiple threads, the JNDI lookup is done again-2?
NOTE- I am doing JNDI lookup at class level. This lookup code is out of service(HttpServletRequest req , HttpServletResponse resp) method.
-----------------------------
@PersistenceContext(name="persistence/LogicalName", unitName="ActualPUNameAsItAppearsInPersistence.xml")
public class RegistrationServlet extends HttpServlet {
@Resource private UserTransaction utx;
Context envCtx = InitialContext().lookup("java:comp/env");
EntityManager em = (EntityManager) envCtx.lookup("persistence/LogicalName");
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
...
utx.begin();
em.persist(credential);
utx.commit();
...
}
...
}
[ November 29, 2008: Message edited by: Amandeep Singh ]