Eclipselink 缓存 - 跨事务保留相同的对象

Eclipselink cache - preserving same object accross transactions

我正在使用 Eclipselink 作为 JPA 提供程序。 以下代码用于访问数据库中的实体:

    em.merge(anEntity);
    em.getTransaction().commit();
    em.getTransaction().begin();
    anEntity2 = em.find(targetClass, anEntity.getId());

有没有办法保证对象 anEntity == anEntity2 将保持不变,即始终 returned 相同的对象引用?例如,以某种方式将 Eclipselink 缓存设置为始终 return 同一实体?

更新 我已阅读以下内容:

In JPA object identity is maintained within a transaction, and (normally) within the same EntityManager. The exception is in a Java EE managed EntityManager, object identity is only maintained inside of a transaction.

来源:link

我的问题是:在 Java EE 环境中,跨事务(通过使用 link 中的变量)assert (employee1 == employee2); 成立吗? 如果没有,是否可以以某种方式绕过此限制?

如 link 所述,唯一的例外是在 Java EE 管理的实体管理器中,因为容器必须控制 EM 的生命周期,并且通常在事务提交时释放它们。您也有句柄的代理将根据需要重新获取下面的 EntityManager,或者如果新事务开始。您可以直接从工厂获取 EntityManager 以避免这种情况,容器也可以为您注入。这使您可以直接控制其生命周期。

在您提供的代码中,尽管 anEntity == anEntity2 不太可能为真,就像您需要对 anEntity 调用 em.merge 一样,它不是托管实例。您需要保留托管实例的句柄,以使其在 EntityManager 的生命周期内保持不变。