@PersistenceContext 如何在线程间管理 EntityManager 和 Session?
结论
在 Spring 常见的 JPA 配置中,@PersistenceContext 注入的是共享的 EntityManager 代理。多个线程可以使用同一个代理,由它把数据库操作转发给当前线程关联的实际 EntityManager。
你的输出符合这种情况:
- 各线程访问同一个注入代理,所以
entityManager.hashCode()相同。 entityManager.unwrap(Session.class)可能返回代理本身,因此它的hashCode()也相同。unwrap(SessionImpl.class)取得了代理背后的 Hibernate 实现对象。System.identityHashCode()不同,说明这些实际对象不同。
这一解释的前提是使用默认的事务型持久化上下文,@Transactional 已生效,并采用常见的 JpaTransactionManager 配置。缺少 beans.xml 和具体依赖版本,仅凭这些日志还无法确定各层代理的细节,可以通过引用比较进一步验证。
ThreadLocal 关联的是实际事务资源
这里需要区分两个对象:
- 注入到 Service 字段中的共享代理。
- 执行数据库操作的实际
EntityManager。
默认情况下,@Service 是单例。不同线程访问同一个 Service 实例,字段中的代理引用也相同,Spring 不会在线程切换时重新给这个字段赋值。
使用常见的 JpaTransactionManager 配置时,一次调用大致经过以下步骤:
- 工作线程通过 Spring 事务代理调用
@Transactional方法。 - 事务管理器为该事务创建或取得实际
EntityManager,将相应资源绑定到当前线程。 - 注入的共享代理执行
find()等操作时,查找当前线程的资源并转发调用。 - 事务完成后,Spring 清理线程绑定,并按资源归属关闭由它创建的
EntityManager。
Spring 的 TransactionSynchronizationManager 使用 ThreadLocal 保存线程关联的事务资源。对于 JPA,这些资源通常以 EntityManagerFactory 为键保存。
三个工作线程可以形成这样的关系:
同一个 EntityManager 代理
├── 工作线程 A 的事务 → 实际 EntityManager A
├── 工作线程 B 的事务 → 实际 EntityManager B
└── 工作线程 C 的事务 → 实际 EntityManager C
线程池会重复使用线程,而事务结束后,Spring 会清理绑定的资源。同一个线程后续开启独立事务时,可以使用另一个实际 EntityManager,并不会永久持有同一个实例。
这种 ThreadLocal 绑定属于 Spring 的事务管理机制,其他 JPA 环境未必采用相同实现。
为什么 unwrap(Session.class) 仍可能返回代理
unwrap() 用于取得指定类型的对象,不保证每次都穿透所有代理层。
Spring 的共享 EntityManager 代理由 SharedEntityManagerCreator 创建。处理 unwrap() 时,如果代理自身已经实现了请求的类型,就可以直接返回自身。
在 Spring 与 Hibernate 的常见集成配置中,共享代理可能同时实现:
jakarta.persistence.EntityManager
org.hibernate.Session
此时,执行:
Session session = entityManager.unwrap(Session.class);
得到的 session 可能与 entityManager 是同一个对象,可以这样比较:
session == entityManager
若结果为 true,两次 hashCode() 调用实际上相当于:
entityManager.hashCode();
entityManager.hashCode();
共享代理会专门处理 hashCode(),无需查找当前事务中的实际 EntityManager。
调用下面的代码时:
entityManager.unwrap(
org.hibernate.internal.SessionImpl.class
);
由于共享接口代理本身不是 SessionImpl,调用需要继续转发到当前线程关联的目标对象,各线程因此可以取得不同的 Hibernate 实例。
另一个示例打印出不同的 Session.hashCode(),可能与配置或取值方式有关。例如,它可能先取得实际 EntityManager,再解包为 Session;也可能使用了不实现 Session 接口的共享代理。需要比较具体配置和代码,才能确定原因。
如何验证代理与实际对象
调试时,可以使用 Spring 的 EntityManagerProxy 取得当前事务中的目标 EntityManager,避免依赖 Hibernate 内部类 SessionImpl。
下面的方法可替换原来的 Service 方法。方法名仍为 updateAccountAsync,执行方式仍是同步的,线程由外部的 ExecutorService 提供。
package org.example.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.example.entity.Account;
import org.hibernate.Session;
import org.springframework.orm.jpa.EntityManagerProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountParallelService {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void updateAccountAsync(Long accountId, String newName) {
// 适用于 Spring 注入的共享 EntityManager 代理。
// 此处应当已经进入事务。
EntityManager target =
((EntityManagerProxy) entityManager)
.getTargetEntityManager();
Session unwrapped = entityManager.unwrap(Session.class);
Session targetSession = target.unwrap(Session.class);
System.out.printf(
"thread=%s, proxyId=%x, unwrapIsProxy=%s, "
+ "targetClass=%s, targetId=%x, sessionId=%x%n",
Thread.currentThread().getName(),
System.identityHashCode(entityManager),
unwrapped == entityManager,
target.getClass().getName(),
System.identityHashCode(target),
System.identityHashCode(targetSession)
);
Account account = entityManager.find(Account.class, accountId);
if (account != null) {
account.setFirstName(newName);
}
}
}
检查日志时,可以关注以下字段:
unwrapIsProxy:为true时,说明unwrap(Session.class)返回了注入代理。targetId:比较各线程对应的值,观察事务背后的实际对象是否不同。targetClass:确认目标对象的类型。
EntityManagerProxy 是 Spring API,适合在这个环境中排查问题。业务操作继续使用注入的 entityManager 即可。
hashCode() 和 System.identityHashCode() 都不是全局唯一编号,不同对象可能发生哈希碰撞。因此,数值相同不能证明是同一个对象;判断两个引用是否指向同一对象,应使用 ==。
原日志中的多行输出交错,是多个线程分别执行 println() 的结果。把线程名和相关标识放进同一次日志调用,更容易看清每个线程对应的对象。
确保事务确实在工作线程中生效
你从 Spring 容器取得 Bean,再由各个工作线程调用它,这种方式可以经过 Spring 事务代理。前提是已正确启用事务管理,并且事务管理器与该持久化单元匹配。可以在 XML 中配置:
<tx:annotation-driven transaction-manager="transactionManager"/>
也可以在 Java 配置中使用 @EnableTransactionManagement。
默认传播行为为 REQUIRED。如果各工作线程原本没有事务,每次调用都会在相应工作线程中开启独立事务。主线程已有的事务不会自动传播到 ExecutorService 的任务中。
还需要检查任务异常。invokeAll() 返回任务的 Future,任务内部抛出的异常需要通过 get() 取得:
List<Future<Void>> futures = service.invokeAll(tasks);
for (Future<Void> future : futures) {
future.get();
}
如果不调用 get(),即使事务或数据库操作失败,主线程也可能看不到对应异常。
使用时需要注意什么
实际的 EntityManager 和 Hibernate Session 不应由多个线程并发使用。共享代理虽然能按线程查找目标,底层实例仍然不是线程安全的。
不要把从某个事务取得的实际 EntityManager、Session 保存到共享字段,或交给其他线程继续使用。并行任务可以像示例中那样传递主键,在各自的事务中重新查询实体。
通过 find() 查询出的 Account 已经是当前持久化上下文中的受管实体。修改属性后,正常情况下会在事务提交时通过脏检查同步到数据库,因此这里无需再调用:
entityManager.merge(account);
示例中的 Thread.sleep(2000) 只会延长事务持续时间,不参与线程绑定,也不能保证并发安全,可以删除。
这套解释适用于默认的 PersistenceContextType.TRANSACTION。如果使用 PersistenceContextType.EXTENDED,持久化上下文的生命周期不同,不能直接套用这里的事务隔离方式,也不应将其放在单例中供多个线程并发访问。
备注:内容仅供参考。
