且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring-Hibernate中的每个线程是否应该有一个EntityManager?

更新时间:2023-01-12 09:04:15

是的,通常EntityManagerSession绑定到线程(实现为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.

或者,也可以使用OpenSessionInViewInterceptorOpenSessionInViewFilter来实现.

Alternatively this can be implemented using OpenSessionInViewInterceptor or OpenSessionInViewFilter.