关于java:JPA \\的commit()方法会使实体分离吗?

Does JPA's commit() method make entity detached?

如今,我一直在搜索JPA实体的生命周期。
但是现在,关于实体生命周期还有一些遗漏之处。我在stackoverflow帖子之一中找到了以下图形,请记住,此图已被修改。

JPA

1
2
3
entityManager.persist(entity);
transaction.commit(); // action completed and entity has become detached.(According to the diagram.)
entityManager.remove(entity); //Attention this step please .

在上一步(提交步骤)中。那么如何去除分离的对象呢?
如果此实体分离,我们都知道不可能管理分离实体,因为它不再具有与持久性上下文的关联。

那么如何删除分离的对象?在这一点上,你能请我澄清一下吗?
在此先感谢!


实体可以通过以下方式之一分离(可能有更多方式):

  • 提交事务(在事务范围的持久性上下文中)时,由持久性上下文管理的实体将分离。

  • 如果关闭了应用程序管理的持久性上下文,则所有托管实体都将分离。

  • 使用清除方法

  • 使用分离方法

  • 回滚

  • 在扩展持久性上下文中,当删除有状态Bean时,所有受管实体都将分离。

  • 我认为问题可能出在应用程序管理的,用户管理的,扩展的持久性上下文之间。


    2件事:
    状态remove和detached是不同的:Removed表示该实体仍处于管理状态,并将在刷新的持久性层中触发删除,Detached表示该实体不再受管理,并且对其进行的更改将不再起作用。不会报告给数据库。

    您的实体状态与entityManager有关。 Managed表示EM跟踪对其所做的所有更改,并将在刷新时将其报告给数据库。

    您必须了解,报告对数据库的更改在事务之外是没有意义的(JPA仅支持对DB的事务访问,并且仅在隔离级别READ_COMMITED中)。

    一旦检索到的事务到期,就跟踪实体上的更改没有任何意义,因为entityManager将无法在事务外部更改数据库状态。

    这就是为什么JPA中的entityManager设计为每个工作单元创建的原因(与persistenceUnit,即为整个应用程序创建一次的entityManagerFactory相反)。

    因此,entityManager应该具有与事务相同的作用域,并且应在提交之后立即释放(这是您让容器为您管理EntityManager生命周期的情况)。

    这也是JPA不支持嵌套事务的原因。


    此图片来自openjpa,但IMO(欢迎其他意见)有点不对?! (在具有TRANSACTION Scope的EE中还可以)
    但是在这样的Java SE示例中:
    ....

    1
    2
    3
    4
    5
    6
    7
    8
    9
    EntityTransaction et = em.getTransaction();
    et.begin();
    em.persist(entity);
    et.commit();
    System.out.println(em.contains(entity)); // true
    em.detach(entity);
    System.out.println(em.contains(entity)); // false
    entity = em.merge(entity);
    System.out.println(em.contains(entity)); // true

    使用分离方法分离实体。提交后,它将停留在实体持久性上下文中。

    对于您的问题:当您有一个分离的对象时,可以使用merge将其重新附加到持久性上下文。


    JPA规范:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    3.3 Persistence Context Lifetime and Synchronization Type
    ...
    An EntityManager with an extended persistence context maintains its references to the entity objects
    after a transaction has committed. Those objects remain managed by the EntityManager, and they can
    be updated as managed objects between transactions.
    ...
    3.3.2 Transaction Commit
    The managed entities of a transaction-scoped persistence context become detached when the transaction
    commits; the managed entities of an extended persistence context remain managed.

    请注意,应用程序管理的实体管理器(通常在Java SE中将使用它)始终使用扩展的持久性上下文。

    因此,您的问题的简短答案是:使用事务范围的PC时,提交将导致脱离;使用扩展PC时,提交不会导致脱离。