Spring-Hibernate中的每个线程是否应该有一个EntityManager? [英] Should there be an EntityManager per thread in Spring-Hibernate?
问题描述
我们正在使用Spring-Hibernate设计一个应用程序,其中6个线程同时运行.每个线程执行不同的操作,并在公共表中插入/更新一些记录(所有线程在公共表上工作).
We are designing an application using Spring-Hibernate where 6 threads run simultaneously. Each thread performs a different operation and inserts/updates a few records in common table(all threads work on common tables).
虽然我们知道我们只能有一个EntityManagerFactory
实例,但是我们不确定应该有多少个EntityManager
实例?我们是否应该创建六个实体管理器(每个线程一个)?我们应该如何创建DAO?我们是否应该像下面那样创建一个EntityManager
并为所有线程使用相同的dao类?我知道EM规范说这不是线程安全的,但是我读到某个地方,在spring的情况下注入EM是线程安全的(不过,我对解释不满意).
While we know that we can have just one single instance of EntityManagerFactory
, we are not sure how many instances of EntityManager
should we have? Should we create six entity managers(one for each thread)? How should we create the DAO? Should we just create one EntityManager
like following and use the same dao class for all the threads? I know EM specification says that it's not thread safe, but I read somewhere that injected EM in the case of spring are threadsafe(I wasn't convinced with the explanation, though).
@Trasactional
public class myAppDao {
@PersistenceContext
private EntityManager entityManager;
..
}
还是我们应该做些不同的事情?
or should we do something different ?
推荐答案
是的,通常EntityManager
或Session
绑定到线程(实现为ThreadLocal变量). Spring IoC/CDI可以识别@PersistenceContext
批注,并对其进行特殊处理以实现此目的.
Yes, usually the EntityManager
or Session
are bound to the thread (implemented as a ThreadLocal variable). @PersistenceContext
annotation is recognized by Spring IoC/CDI and is treated in a special way to enable this.
您的应用程序中有一层(通常标记为@Transactional
)可创建EntityManager并将其绑定到ThreadLocal变量.每次调用第一个@Transactional
时都会发生这种情况.同样,每次退出该方法时,EntityManager
都会关闭.
There is some layer in your app (usually marked as @Transactional
) that creates EntityManager and binds it to the ThreadLocal variable. This happens every time the 1st @Transactional
is invoked. And same - EntityManager
is closed every time the method exits.
或者,也可以使用OpenSessionInViewInterceptor
或OpenSessionInViewFilter
来实现.
Alternatively this can be implemented using OpenSessionInViewInterceptor
or OpenSessionInViewFilter
.
这篇关于Spring-Hibernate中的每个线程是否应该有一个EntityManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!