本文介绍了通过@PersitenceContext或@PersitenceUnit注入EntityManagerFactory吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我一直认为@PersistenceContext用于将EntityManager注入到容器管理的应用程序中,而@PersistenceUnit用于注入EntityManagerFactory.

I've always thought that @PersistenceContext was for injecting EntityManager into a container-managed application, while @PersistenceUnit was for injecting an EntityManagerFactory.

Javadoc说

对于PersistenceUnit( http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceUnit.html )

For PersistenceUnit (http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceUnit.html)

对于PersistenceContext( http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html )

And for PersistenceContext (http://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html)

到目前为止,一切都很好,但是随后我正在阅读JPA教程(请参见 https://docs.oracle.com/cd/E19798-01/821-1841/bnbqy/index.html ),其中包含类似的示例

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

@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();
}

如果我们在谈论应用程序托管代码,那么PersistenceContext也可以引用EntityManagerFactory吗?

so the PersistenceContext can also refer to an EntityManagerFactory if we're talking about an application managed code?

免责声明-与我猜出的这个问题的答案无关- PersistenceUnit vs PersistenceContext

disclaimer -- not related to the answers from this question I guess -- PersistenceUnit vs PersistenceContext

推荐答案

是的.

我想JPA教程的示例是一个粗心的错误.先前在应用程序管理的实体管理器"的同一部分中,其编写为

I guess the example of the JPA tutorial is a careless mistake. Previously in the same section 'Application-Managed Entity Managers' it's written

@PersistenceUnitEntityManagerFactory emf;

@PersistenceUnit EntityManagerFactory emf;

然后从EntityManagerFactory实例获取EntityManager:

Then obtain an EntityManager from the EntityManagerFactory instance:

EntityManager em = emf.createEntityManager();

EntityManager em = emf.createEntityManager();

这篇关于通过@PersitenceContext或@PersitenceUnit注入EntityManagerFactory吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 22:09