I've always thought that @PersistenceContext was for injecting EntityManager into a container-managed application, while @PersistenceUnit was for injecting an EntityManagerFactory.
Javadoc says
For PersistenceUnit (http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceUnit.html)
Expresses a dependency on an EntityManagerFactory and its associated persistence unit.
And for PersistenceContext (http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html)
Expresses a dependency on a container-managed EntityManager and its associated persistence context.
So far so good, but then I was reading the JPA tutorial (see https://docs.oracle.com/cd/E19798-01/821-1841/bnbqy/index.html) that contains an example like this
The following example shows how to manage transactions in an application that uses an application-managed entity manager:
@PersistenceContext
EntityManagerFactory emf;
EntityManager em;
@Resource
UserTransaction utx;
...
em = emf.createEntityManager();
try {
utx.begin();
em.persist(SomeEntity);
em.merge(AnotherEntity);
em.remove(ThirdEntity);
utx.commit();
} catch (Exception e) {
utx.rollback();
}
so the PersistenceContext can also refer to an EntityManagerFactory if we're talking about an application managed code?
disclaimer -- not related to the answers from this question I guess -- PersistenceUnit vs PersistenceContext
I've always thought that @PersistenceContext was for injecting EntityManager into a container-managed application, while @PersistenceUnit was for injecting an EntityManagerFactory.
That's true.
I guess the example of the JPA tutorial is a careless mistake. Previously in the same section 'Application-Managed Entity Managers' it's written
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:
@PersistenceUnit EntityManagerFactory emf;
Then obtain an EntityManager from the EntityManagerFactory instance:
EntityManager em = emf.createEntityManager();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With