Search code examples
javajpaeclipselink

Eclipselink cache - preserving same object accross transactions


I'm working with Eclipselink as a JPA provider. The following code is used to access entities from the database:

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

Is there a way to guarantee that the object anEntity == anEntity2 will hold, that is always the same object reference is returned? For example somehow setting Eclipselink cache to always return the same entity?

UPDATE I've read the following:

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.

Source: link

My question is this: in a Java EE environment, across transactions, (by using the variables in the link) does assert (employee1 == employee2); hold? If not, is it possible to somehow bypass this limitation?


Solution

  • As the link states, the only exception is within a Java EE managed entityManager, as the container must control the EM's lifecycle, and generally releases them when the transaction commits. The proxy you have a handle too will then re-obtain an EntityManager underneath as needed, or if a new transaction starts. You can obtain the EntityManager directly from the factory though to avoid this situation, which the container can inject for you as well. This allows you to control its lifecycle directly.

    In the code you have provided though it is unlikely that anEntity == anEntity2 would be true, as if you need to call em.merge on anEntity, it is not a managed instance. You need to keep a handle on the managed instance for it to remain constant for the life of the EntityManager.