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
?