Embedding EntityManager in a servlet does not seem to be thread safe

I want to create a Java EE login application. I was thinking of implementing it using the html page, servlet and entity class for the user, but it seems that the EntityManager not thread safe (cannot be injected into the servlet, and I need to check the database for it).

I read about EntityManagerFactory , but I do not want to control the life of the created EntityManager when I can make a container. I think that some implementation using the DAO template can be done in such a way that I can have an entity manager in the servlet, something like a DAOImpl containing the manager, and have this class as a private variable in the servlet. But I could not find useful tutorials on the Internet.

Can someone provide an implementation for this?

+5
source share
2 answers

The path to creation is to create a LoginService as @Stateless. It must contain an EntityManager. This EJB concern manages the login.

Now enter the EJB in your servlet.

The container will take care of concurrency.

http://www.adam-bien.com/roller/abien/entry/is_in_an_ejb_injected

+1
source

Follow the suggested Oracle documentation here , any approach should do: Either:

Inject an EntityManagerFactory into a dao impl via SerlvetContextListener.

  @PersistenceUnit private EntityManagerFactory emf; 

Or embed EntityManager in your DaoImpl.

 @PersistenceContext private EntityManager em; 
+1
source

All Articles