2

Assume a simple JPA entity class like this:

@Entity(name="TASK")
public class Task implements Serializable {
    /* getters/setters omitted for brevity */

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date done;
}

How can I use the JPA 2 TypedQuery, CriteriaQuery and the metamodel to do the equivalent of a simple UPDATE TASK SET done = ? WHERE id = ? SQL query? Everything I could find on the net would result in using JPA like this

Query q = em.createQuery(
  "UPDATE TASK SET done = :date WHERE id = :id");
q.setParameter(/* set date and id */);
q.executeUpdate();

Can this be done with a TypedQuery instead?

Waldheinz
  • 10,399
  • 3
  • 31
  • 61

1 Answers1

1

The JPA way you are supposed to do such operation is letting CriteriaQuery select the item(s) to be modified, and loop over them by using plain Java, then modify them using merge() method. Something like:

Date d;
CriteriaQuery<Task> cq = cb.createQuery(Task.class);
...
TypedQuery<Task> tq = em.createQuery(cq);
List<Task> tasks = tq.getResultList();
for (Task task : tasks) {
    task.setDone(d);
    em.merge(task);
}
// or
Task task = tq.getSingleResult();
task.setDone(d);
em.merge(task);

See this answer for further reference.

Community
  • 1
  • 1
perissf
  • 15,979
  • 14
  • 80
  • 117
  • 2
    Thanks for the answer. My concern with this approach is that it seems as it would result in repeated read-modify-write cycles, while a simple SQL update statement would allow the DB to make the updates without transferring all affected rows to the client and back to the DB. Depending on the number of affected rows, this can make quite a difference. Or is the JPA layer capable of optimizing the RMW cycle away? – Waldheinz May 27 '12 at 16:43
  • I understand your concern and I think that, for the additional client-server round-trip thing, you are right. However there a number of optimizations you can deal with. See this link for example: http://java-persistence-performance.blogspot.com/2011/06/how-to-improve-jpa-performance-by-1825.html – perissf May 27 '12 at 16:53