Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Detach a list of attached read-only entities

Tags:

jpa

jakarta-ee

Is it beneficial to detach entities of large lists after querying, i.e. use a default pattern for those entities like:

// Find all
for List<Device> devices = em.createNamedQuery("find.*.devices", Device.class).getResultList();

// Detach all
for (Device d : devices) {
  em.detach(d);
}

We could avoid some kinds of negative effects like erroneously update the database for entities considered as "read only" (which could be guaranteed) or save memory.

like image 235
John Rumpel Avatar asked Dec 01 '25 03:12

John Rumpel


1 Answers

If you want to use a list without any updates in the database your can get the objects detached.

You have the following options:

  1. Do not open a transaction if you are using programatic transaction. Notice that the transaction was not opened:

    EntityManager em = EntityManagerFactory.createEntityManager();

    List personList = em.query()

  2. Mark your method as transaction not suported @TransactionAttribute(NOT_SUPPORTED)

  3. If you clear your EntityManager you will detach all enties: em.clear()
like image 88
uaiHebert Avatar answered Dec 05 '25 00:12

uaiHebert