0

can we not use an EntityManager in Servlet ? like this :

@WebServlet(name = "ServletPrincipal", urlPatterns = { "/test" })
public class ServletPrincipal extends HttpServlet {


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


EntityManagerFactory emf = Persistence.createEntityManagerFactory("todo");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
for (int i = 0; i < 10; i++) {
Voiture car = new Voiture(0, "b", "c");
em.persist(car);
}

em.getTransaction().commit();

Query q1 = em.createQuery("SELECT COUNT(v) FROM Voiture v");
System.out.println("Le nombre d'enregistrement: "
+ q1.getSingleResult());

TypedQuery<Voiture> query = em.createQuery("SELECT v FROM Voiture v",
Voiture.class);
List<Voiture> results = query.getResultList();
for (Voiture p : results) {
System.out.println(p.getMatricule());

}
// Close the database connection:
em.close();
emf.close();

    }

}

if you can not, then how can use persistence in one servlet?

and why?

i use tomcate7, servlet3,jpa2, and java EE 6 thank you very much

user1528481
  • 45
  • 1
  • 4

3 Answers3

0

It is perfectly fine to use EntityManager in Servlet.

Because your servlet can (and likely will) serve multiple request same time and because EntityManager is not thread safe, you should not assign (and also not inject) instance of entityManager to the field in servlet.

What you can, and probaly should do, is to create instance of EntityManagerFactory only once and reuse it. EntityManagerFactory is costly object to create and using it for simultaneous request is fine, because it is thread safe.

If this servlet is only place where you you need this persistence unit, you can for example open EntityManagerFactory in servlet's init-method and close it in destroy-method.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
0

Normally it is not a good idea to keep the persistence code in your controller servlet. But to answer your question, as @Mikko Maunu rightly said, you can use entity manager in your servlet.

Ripan
  • 26
  • 1
0

Also use of @PersistenceContext and @PersistenceUnit to pass reference to EntityManager and EntityManagerFactory is a good idea. Also consider EMFactory is thread safe and EM is not.

Koitoer
  • 18,778
  • 7
  • 63
  • 86