English 中文(简体)
使用 JPA 2 Typed 查询来更新
原标题:Using a JPA 2 TypedQuery for updates
  • 时间:2012-05-26 19:32:05
  •  标签:
  • java
  • jpa-2.0

假设一个简单的 JPA 实体类 像这样 :

@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;
}

我怎样才能使用 JPA 2 < code> TypedQuery 、 CriteriaQuery 和元模型来做简单 UPDATE TASK SET 完成 =? where id =? SQL 查询?

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

可以用 < code> TypedQuery 代替 < code> 查询 完成吗?

最佳回答

JPA 操作的方式是让标准查询选择要修改的项目, 使用平面 Java 环绕它们, 然后使用 < code> merge () 方法修改它们。 类似 :

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);

,以进一步参考。

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签