java – Better definition of EntityManager

Question:

I'm studying about JPA along with Dependency Injection and read some 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 entering the persistence unit that is defined in the persistence.xml file and creating our EntityManager .

I also read that we can use it like this:

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

Do both above have the same effect?

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

Answer:

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

The best approach is the injection so you don't have to instantiate anything or worry about how this object comes and everything else, java and hibernate take care of everything and bring it back to you, you just need an annotation on top of your attribute of class usually and that's it, MAGIC. I think it's really interesting to use dependency injection because when you inject it, at least CDI takes care of closing the connections, which helps a lot, it's usually hard to close the connections correctly without leaving anyone without it. ..

The @PersistenceContext should be used inside a @Repository class, as a good practice, but if you want to use it outside of that, as far as I know, nothing prevents it, do tests, write small code, see the errors happen and share with us the results of your questions there.

Scroll to Top