java - Inject a EntityManagerFactory through @PersitenceContext or @PersitenceUnit? -
i've thought @persistencecontext injecting entitymanager container-managed application, while @persistenceunit injecting entitymanagerfactory.
javadoc says
for persistenceunit (http://docs.oracle.com/javaee/7/api/javax/persistence/persistenceunit.html)
expresses dependency on entitymanagerfactory , associated persistence unit.
and persistencecontext (http://docs.oracle.com/javaee/7/api/javax/persistence/persistencecontext.html)
expresses dependency on container-managed entitymanager , associated persistence context.
so far good, reading jpa tutorial (see https://docs.oracle.com/cd/e19798-01/821-1841/bnbqy/index.html) contains example this
the following example shows how manage transactions in application uses 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 persistencecontext can refer entitymanagerfactory if we're talking application managed code?
disclaimer -- not related answers question guess -- persistenceunit vs persistencecontext
i've thought @persistencecontext injecting entitymanager container-managed application, while @persistenceunit injecting entitymanagerfactory.
that's true.
i guess example of jpa tutorial careless mistake. in same section 'application-managed entity managers' it's written
to obtain entitymanager instance, first must obtain entitymanagerfactory instance injecting application component means of javax.persistence.persistenceunit annotation:
@persistenceunit entitymanagerfactory emf;
then obtain entitymanager entitymanagerfactory instance:
entitymanager em = emf.createentitymanager();
Comments
Post a Comment