2

In my application I need most objects fetched in detached mode (fetched with the find API).
I'm wondering if there is a way to ask a detached object from the JPA provider and save the extra call to detach() API.
In additional I would expect the object created in such mode to be less expensive since the JPA provider doesn't need to add it to the entity manager context.
Is there a way to achieve this with JPA APIs?
Is there a way to achieve such functionality with query results?

  • Specifically I'm using Eclipse Link so if there is a specific way to do it with this implementation it will be helpful as well.
Avner Levy
  • 6,601
  • 9
  • 53
  • 92

1 Answers1

2

You can fetch a detached entity without an extra call to detach() if you fetch it outside a transaction. If you are not using container-managed transactions, it's trivial, simply do not start a transaction.

If you are using CMT, you have to make sure the requesting object is not a transaction-enabled EJB:

  • if in an EJB, suspend the transaction by annotating the appropriate method with:@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED),

or

  • call the EntityManager from a POJO. You dont have to call it directly, it only impotrant that the query result will end in a non-EJB object.

AFAIK, there is no performance gain to be expected, since the query result will always be put in the current persistence context, however shortlived it may be.

EDIT: There is another possibility to get detached objects which does not depend on transaction demarcations: JPA constructor expressions:

List<DTO> dtos = em.createQuery("SELECT NEW com.example.DTO( o.title, o.version) FROM Entity o").getResultList();

The constructed type must have a constructor with all the relevant attributes. The objects in the list, entities or not, will always be created detached. However there is a small overhead of instantiating a new object.

kostja
  • 60,521
  • 48
  • 179
  • 224