Better EntityManager definition

3

I'm studying JPA together with Dependency Injection and read a few points about EntityManager :

If we use the following method:

public EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("exemplo");
EntityManager entityManager = factory.createEntityManager();
factory.close();
return entityManager;
}

We are informing the persistence unit that is defined in the file persistence.xml and creating our EntityManager .

I also read that we can use this way:

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

Both above have the same effect?

Regarding Dependency Injection with CDI I have read that by using @Inject on a EntityManager object within a DAO for example, the entityManager object will have all its dependencies populated. But if we want to tell CDI how EntityManager must be instantiated, we can create a method in a class X with the annotation @Produces . Another question: Can @Produces together with @PersistenceContext be used in getEntityManager() method? To load the persistence unit defined in the persistence.xml file or to create our EntityManager must be the main method? Or are these resources already read when starting an application server, in my case wildfly ?

    
asked by anonymous 28.12.2016 / 18:22

1 answer

0

Basically and the same thing, the crucial difference at this point is that in one, the JVM does its magic to create its EntityManager and in the other you have a JPAUtil class that brings you this Entity.

The best approach is the injection so you do not have to instantiate anything and do not worry about how this object comes and everything, java and hibernate take care of everything and get you back, just need an annotation up of your class attribute usually and ready, MAGIC. I think it is very interesting to use dependency injection because when you inject it, at least CDI takes care of closing the connections, which already helps a lot, it usually works to close the connections correctly without leaving anyone without her ...

@PersistenceContext should be used inside a @Repository class, as a good practice, but if you want to use it outside of it, as far as I know, nothing prevents it, make tests, write small codes, see the errors happen and share with we'll get the results of your questions there.

    
15.02.2017 / 18:30