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?
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:See this answer for further reference.