1

I am starting to learn JPA and EJB, and when I deal with some examples, I saw there are two kinds of creating EntityManager, using @PersistenceContext and using EntityManagerFactory:

@PersistenceContext(unitName ="somename")
private EntityManager entityManager;

and

EntityManagerFactory emf = Persistence.createEntityManagerFactory("somename");
EntityManager em = emf.createEntityManager();

I am not really clear if these two approaches are the same or not. Can anyone explain me what are the differences between them and if they are the same, which one is "newer" nowadays for creating JavaEE Applications.

Thank you.

Ock
  • 944
  • 3
  • 9
  • 27
  • 2
    First one uses annotations, the second one a factory. at the end both is the same – Jens Aug 29 '17 at 12:17
  • 2
    They are not quite the same, as annotations allow container managed injection while the factory approach forces you to manage the lifecycles yourself. You must close the resources when done. – Chris Aug 29 '17 at 13:31
  • 1
    @Sonn your question essentially boils down to: https://stackoverflow.com/questions/13489057/differences-between-container-managed-and-application-managed-entitymanager and https://stackoverflow.com/questions/8432046/application-vs-container-managed-entitymanager – crizzis Aug 29 '17 at 15:22

0 Answers0