Better definition of Entitymanager

Asked

Viewed 282 times

3

I’m studying on JPA along with the Dependency Injection and read some points on the 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 set in the file persistence.xml and creating our EntityManager.

I also read that we can use so:

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

Both above has the same effect ?

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

  • @PersistenceContext is used when you have more than one persistence unit. Usually when your application works with multiple banks. When it is necessary to say which of them you want to persist, edit or read data. Now about dependency injection, scope and transaction management, etc. I suggest you read about the Spring Framework. It makes these tasks much easier, has excellent documentation and a very active community.

1 answer

0

Basically and the same thing, the crucial difference at this point is that in one, 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 don’t have to instantiate anything and not worry about how this object comes and everything, java and Hibernate take care of everything and back for you, just need an Annotation on top of your class attribute usually and ready, MAGIC.I find it very interesting to use dependency injection because when you inject it, at least CDI takes care to close the connections, which already helps enough, usually from work close the connections in the correct way without leaving anyone without it...

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.