【问题标题】:Does spring data jpa create new instance of EntityManager for each transaction?spring data jpa 是否为每个事务创建 EntityManager 的新实例?
【发布时间】:2018-09-30 02:40:17
【问题描述】:

我在 spring data jpa 应用程序中找不到有关 EntityManager 和事务之间关系的信息。

以下哪一项是正确的:

  1. EntityManager 的新实例为每个事务创建
  2. EntityManager 的一个共享实例用于所有事务

【问题讨论】:

  • 我假设事务是指使用@Transactional 注释?
  • 这有关系吗? @Transactional 注解只是事务管理的一种方式。

标签: jpa transactions spring-data-jpa entitymanager spring-transactions


【解决方案1】:

正确答案是:EntityManager 的一个共享实例用于同一持久性上下文中的所有事务。

我们可以在这里考虑两件事:

首先,EntityManager 接口中的definition

EntityManager 实例与持久性上下文相关联。持久性上下文是一组实体实例,其中对于任何持久性实体身份,都有一个唯一的实体实例。在持久化上下文中,管理实体实例及其生命周期。

可由给定 EntityManager 实例管理的实体集由持久性单元定义。持久性单元定义了由应用程序相关或分组的所有类的集合,并且必须在它们到单个数据库的映射中并置。

二、Spring SimpleJpaRepository的构造函数:

public SimpleJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {


    Assert.notNull(entityInformation, "JpaEntityInformation must not be null!");
    Assert.notNull(entityManager, "EntityManager must not be null!");


    this.entityInformation = entityInformation;
    this.em = entityManager;
    this.provider = PersistenceProvider.fromEntityManager(entityManager);
}

em 是在该类中使用final 修饰符定义的属性:

private final EntityManager em;

并且在SimpleJpaRepository 的方法中调用em 而不创建EntityManager 的新实例。

【讨论】:

  • 不确定这是否正确。尽管 SimpleJpaRepository 中的 EntityManager 字段是最终的并且 SimpleJpaRepository 不会创建 EntityManager 的新实例,但我在调试模式下看到 EntityManager 是代理。因此可以隐藏 EntityManager 的新实例的创建。
猜你喜欢
  • 2019-01-18
  • 2011-08-23
  • 2017-08-15
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多