Featured Post

Scalability Techniques

Scalability is about the capability of a system to manage the increase workload of a system without causing qualities impact (i.e. perfo...

Monday, July 2, 2012

JPA EntityManager and EntityManagerFactory

One of the most important things to know about the EntityManager interface is that it's not thread safe. If a Servlet or any kind of stateless component uses the EntityManager as a shared instance, you can encounter many problems.

EntityManager


MyServlet.java

 ...

@Entity
public class MyServlet extends HttpServlet {

  @PersistenceContext(unitName="myUnit")
  private EntityManager em;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
   ...

}
The above snippet of code is not correct.

EntityManagerFactory


MyServlet.java

 ...

@Entity
public class MyServlet extends HttpServlet {

  @PersistenceUnit(unitName="myUnit") 
  private EntityManagerFactory factory;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  EntityManager em = emf.createEntityManager()

   ...

}
The above snippet of code is correct.

No comments :

Post a Comment