@PersistenceContext如何在多线程环境中处理,特别是在EntityManager与 Session方面

后端开发 2026-07-09

我遇到了一个问题,正在努力弄清楚发生了什么。据我所知,使用@PersistenceContext会在我的类中注入一个EntityManager。它应该是线程感知的,通过使用ThreadLocalEntityManager绑定到一个线程。然而,看看我的代码:

package org.example.service;

import org.example.entity.Account;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.Session;
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) {
        Session session = entityManager.unwrap(Session.class);
        org.hibernate.internal.SessionImpl realSession =
                entityManager.unwrap(org.hibernate.internal.SessionImpl.class);
        System.out.println("Session code: " +entityManager.unwrap(Session.class).hashCode());
        System.out.println("Thread code: " + Thread.currentThread().hashCode());
        System.out.println("Entity " + entityManager.hashCode());
        System.out.println("realSession " + System.identityHashCode(realSession));
        Account acc = entityManager.find(Account.class, accountId);
        if (acc != null) {
            acc.setFirstName(newName);
            entityManager.merge(acc);
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}

当我用三个线程来调用这个方法时,它确实在三条不同的线程上执行成功。然而,它会打印出SessionEntityManager的哈希码相同,尽管SessionImpl的哈希码对每个线程来说都是不同的。

我看到一个朋友写了类似的代码,在那里Session的哈希码对每个线程都不同,但不幸的是,我没有他的代码可供比较。我是Spring的新手,仍在学习。

package org.example;

import org.example.service.AccountParallelService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainApp {

    public static void main(String[] args) {
        System.out.println("Starting Spring Application Context...");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        AccountParallelService parallelService = context.getBean(AccountParallelService.class);
        try {
            ExecutorService service = Executors.newFixedThreadPool(5);

            List<Callable<Void>> tasks = new ArrayList<>();
            tasks.add( () -> { parallelService.updateAccountAsync(1L, "Thread_Name_1"); return null; });
            tasks.add(() -> { parallelService.updateAccountAsync(2L, "Thread_Name_2"); return null; });
            tasks.add(() -> { parallelService.updateAccountAsync(3L, "Thread_Name_3"); return null; });
            service.invokeAll(tasks);
            service.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("\nShutting down Spring Context...");
            context.close();
        }
    }
}
the out put
Session code: 62790143
Session code: 62790143
Thread code: 498198174
Session code: 62790143
Thread code: 2143293285
Entity 62790143
Thread code: 95675270
Entity 62790143
realSession 1071349779
realSession 620176498
Entity 62790143
realSession 105967982

解决方案

首先,entityManager是由Spring Framework注入的一个代理对象:

@PersistenceContext
private EntityManager entityManager;

这是一个供所有线程共享的代理对象,属于单例。

让我们看看:

log.info("thread: {} - em.toStr: {}", Thread.currentThread().getName(), entityManager);
log.info("thread: {} - em.class: {}", Thread.currentThread().getName(), entityManager.getClass());

// output:
thread: pool-2-thread-2 em.toStr: Shared EntityManager proxy for target factory [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@1978d891]
thread: pool-2-thread-1 em.toStr: Shared EntityManager proxy for target factory [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@1978d891]
thread: pool-2-thread-2 em.class: class jdk.proxy1.$Proxy189
thread: pool-2-thread-1 em.class: class jdk.proxy1.$Proxy189

原因如下:在使用entityManager时,代理会先检查当前线程是否已经关联了一个Hibernate会话。
如果已关联,则会使用该会话。
如果没有,则会创建一个新的会话。

使用unwrap方法不会返回会话,但仍然是同一个代理:

Session session = entityManager.unwrap(Session.class);
log.info("unwrapped tostr: {}", session);
log.info("unwrapped class: {}", session.getClass());

// output
unwrapped tostr: Shared EntityManager proxy for target factory [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@1978d891]
unwrapped class: class jdk.proxy1.$Proxy189

只有在我们使用entityManager从数据库获取东西时,才会创建一个新会话或检索已绑定到线程的会话:

Person p = entityManager.find(Person.class, id);

entityManager.find调用SharedEntityManagerCreator.invoke()

SharedEntityManagerCreator.invoke()内会发生以下情况:

...
// Determine current EntityManager: either the transactional one
// managed by the factory or a temporary one for the given invocation.
EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager(
  this.targetFactory, this.properties, this.synchronizedWithTransaction);
...
if (target == null) {
  logger.debug("Creating new EntityManager for shared EntityManager invocation");
  target = (!CollectionUtils.isEmpty(this.properties) ?
    this.targetFactory.createEntityManager(this.properties) :
    this.targetFactory.createEntityManager());                 // -- HERE --
  isNewEm = true;
}

上述标记的代码中创建的真正的entityManager如下:

this.targetFactory.createEntityManager()

在Hibernate的情形下,创建的entityManagerSessionImpl类的对象。

所有操作都将使用这个特定的SessionImpl实例来执行,而这个实例对每个线程来说都是不同的。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章