6

I want to make a login app in Java EE. I thought of implementing it using a html page, a servlet and an entity class for the user, but it seems that EntityManager is not thread safe (can't be injected in the servlet and I need it to check the database) .

I read about EntityManagerFactory but I don't want to manage the life of the produced EntityManager when I can have the container do it. I think that some implementation using the DAO pattern could be made so that I can have an entity manager in the servlet, something like DAOImpl containing a manager, and have that class as a private variable in the servlet. But I couldn't find any useful tutorials online.

Could someone provide an implementation for this?

2
  • An object can only be not thread safe if it has mutable state. So why not perform your authentication with a stateless object. Isn't this the sort of thing that a @Stateless Session Bean is for (part of EJB 3.0)?
    – scottb
    May 24, 2015 at 10:43
  • How exactly are you injecting it which made you think that it's not thread safe?
    – BalusC
    May 25, 2015 at 19:41

2 Answers 2

2
+50

The way to go is to create a LoginService as @Stateless. It should contains the EntityManager. This EJB concern is manage login.

Now Inject the EJB into your servlet.

The container will take care about the concurrency.

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

1
1

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

Injecting EntityManagerFactory in your dao impl via SerlvetContextListener.

 @PersistenceUnit        
 private EntityManagerFactory emf;

Or Injecting the EntityManager in your DaoImpl.

@PersistenceContext
    private EntityManager em;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.