当我们需要多个EntityManager时? [英] When we need more than one EntityManager?
问题描述
我正在学习JPA并有一个问题:
在哪些情况下我们需要多个 EntityManager
in我们的申请?
我所知道的两种情况如下:
-
当我们的应用程序是多线程应用程序并且多个线程需要JPA事务时,因为
EntityManager
不是线程安全的,我们需要一个每个线程的EntityManager
。 -
当任何线程需要多个并发事务时,我们需要多个
EntityManager
在该线程中,因为EntityManager
和EntityTransaction $ c $之间存在一对一的关系c>。
Q1。当我们需要多个 EntityManager
?
Q2时,还有其他情况吗?根据我的理解,每个Persitence单元应该只有一个 EntityManagerFactory
。我对么?如果没有,那么当我们需要多个 EntityManagerFactory
每个持久性单元时会出现什么情况?
Q1: EntityManager
最好与老旧的Hibernate Session
进行比较:工作单元(简单的业务操作,例如登录用户,下订单等)。它不一定与单个线程相关联。如果不同的线程执行在单个工作单元内相互依赖的DB任务,则只会遇到麻烦。您需要同步执行它们(最好是在单个线程中按顺序执行)。例如,如果您在用户登录时有业务要求清理一些旧日志(这可能不会打扰彼此的信息),您可以在一个工作单元内的两个独立线程中完美地执行它。 / p>
Q2:您的理解是正确的。但是,您可以创建多个,但这没有任何意义,也没有任何好处。它只会增加很大的开销。
I am learning JPA and have one question:
In which situations we need more than one EntityManager
in our application?
The two situations that I am aware of are as follows:
When our application is a multi-threaded application and more than one thread needs JPA transaction because
EntityManager
is not thread-safe and we need oneEntityManager
per thread.When any of the thread needs multiple concurrent transactions, we need more than one
EntityManager
in that thread because there is one-to-one relationship betweenEntityManager
andEntityTransaction
.
Q1. Are there any other situations when we need more than one EntityManager
?
Q2. Upto my understanding, there should be only one EntityManagerFactory
per Persitence Unit. Am I correct? If not, then what are those situations when we need multiple EntityManagerFactory
per Persistence Unit?
Q1: The EntityManager
is best to be compared with the "good old" Hibernate Session
: an unit of work (a simple business action, e.g. "logging in an user", "placing an order", etc). It is not necessarily tied to a single thread. You will only run in trouble if the different threads execute DB tasks which depends on each other inside a single unit of work. You would need to execute them in sync (preferably, in order in a single thread). If you for example have the business requirement to clean up some "old logs" when an user logs in (which reasonably wouldn't disturb each other's information), you can perfectly execute it in two separate threads inside a single unit of work.
Q2: Your understanding is correct. You can however create more than one, but that wouldn't make any sense nor have any benefits. It would only add significant overhead.
这篇关于当我们需要多个EntityManager时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!