问题描述
在少数项目中,我已成功使用
In few project I have been successfully using
@PersistenceUnit(unitName = "MiddlewareJPA")
EntityManagerFactory emf;
...
EntityManager entityManager = emf.createEntityManager();
获取数据库连接的 EntityManager
,但是几天前我试图将我的项目移动到 Jboss EAP 6.2
,它无法创建 EntityManager
。我在谷歌搜索它,我发现我应该尝试将 @PersistenceUnit
改为
to obtain EntityManager
for Database connection, but some days ago I was trying to move my project to Jboss EAP 6.2
and it couldn't create EntityManager
. I was googling it and I found that I should try change @PersistenceUnit
to
@PersistenceContext(unitName = "MiddlewareJPA")
private EntityManager entityManager;
获取 EntityManager 。它工作但我不知道为什么。 PersistenceUnit
和 PersistenceContext
之间有什么区别?每个人的利弊是什么?我们应该在哪里使用其中一个?
to obtain EntityManager. It worked but I don't know why. What is the difference bettween PersistenceUnit
and PersistenceContext
? What are pros and cons of each one? Where should we be using one of them?
推荐答案
我不知道它在Java EE中是如何工作的,但在Spring中,当你指定<$ c $时c> @PersistenceContext 注释,它注入 EntityManager
。它在哪里 EntityManager
?通过调用 EntityManagerFactory.createEntityManager()
为整个应用程序生命周期创建一个 EntityManager
是错误的。因此,使用并直接实例化 EntityManager
接口的特殊实现。它有一个内部可变线程本地引用 real EntityManager
。方法的实现只是将调用重定向到此真实 EntityManager
。并且有一个servlet监听器,在每个请求之前通过调用 EMF.createEntityManager()
获取 EM
并将其分配给特殊 EM
的内部引用。此侦听器还通过调用 getTransaction()。begin()
, .commit()
和<$ c $来管理事务。 real EM
上的c> .rollback()。这是对已完成工作的非常简化的描述。而且我相信,JEE容器的功能和Spring一样。
I don't know how it works exactly in the Java EE, but in Spring, when you specify @PersistenceContext
annotation, it injects EntityManager
. Where does it get EntityManager
? It is wrong to create one EntityManager
for the whole application lifetime by calling EntityManagerFactory.createEntityManager()
. So instead a special implementation of EntityManager
interface is used and instantiated directly. It has an internal mutable thread-local reference to a real EntityManager
. Implementations of methods just redirect calls to this real EntityManager
. And there is a servlet listener, that before each request obtain EM
by calling EMF.createEntityManager()
and assign it to that inner reference of special EM
. Also this listener manages transactions by calling getTransaction().begin()
, .commit()
and .rollback()
on the real EM
. It is very simplified description of performed work. And I believe, that JEE container does the same thing, as Spring does.
一般情况下,最好注入 EntityManager
,因为 EntityManagerFactory
和 @PersistenceUnit
你应该创建/销毁 EntityManager
每次都是手工管理交易。
In general case it is better to inject EntityManager
, because with EntityManagerFactory
and @PersistenceUnit
you should create/destroy EntityManager
every time by hands and manage transactions too.
这篇关于PersistenceUnit vs PersistenceContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!