Are JPA Query objects returned by EntityManager reusable?

Let's say I create JPA requests in a loop:

for(A elem : collection) {
  emanager.createQuery("update A a set a.x=:y where a.id=:id")
          .setParameter("id",elem.id)
          .setParameter(":y", 123)
          .executeUpdate();
}

Is it possible to reuse the returned instance Query?

Query query = emanager.createQuery("update A a set a.x=:y where a.id=:id");
for(A elem : collection) {
  query
          .setParameter("id",elem.id)
          .setParameter(":y", 123)
          .executeUpdate();
}

Does it apply to all instances Query? NamedQuery, NativeQueryetc. Of course, I'm talking about reusing an instance in the same EntityManager, i.e. As part of the same transaction

+5
source share
3 answers

Reused for request. How much I tried to work.

-1
source

, () , " " . createQuery , . , . , JPQL - NamedNativeQuery.

0

Why aren't you trying to use EntityManager methods to save, update, delete registers in the database?

emanager.persist(elem); // creates a register in the database, set the annotation for autoincrement id of new registers in the Entity for better performance.

emanager.merge(elem); // updates a register in the database, chance the values of the Entity values and merge to persist changes to the register.

emanager.remove(emanager.merge(elem)); // delete registers from database, you need to merge de entity before deleting to avoid deleting problems.

so that you can do this and will work fine:

for(A elem : collection) emanager.merge(elem);
-4
source

All Articles