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.– Cleo