[英]Can I update multiple columns of table by query language using JPA
I created one table like student and I fetched the address based on age (like age = 22). 我创建了一个像学生一样的表,我根据年龄(如年龄= 22)获取了地址。 Now I want to update the address based on age "22" to all address columns of table. 现在我想将基于年龄“22”的地址更新到表的所有地址列。 How can I do this? 我怎样才能做到这一点?
Below is my code: 以下是我的代码:
public static void main(String[] args) {
EntityManager entityManager = Persistence.createEntityManagerFactory(
"demoJPA").createEntityManager();
Query query = entityManager.createQuery("SELECT student FROM Student student WHERE student.age = 22");
System.out.println("Data is" + query.getResultList().size());
List<Simpletable> simpletable = query.getResultList();
for (Simpletable simpletable1 : simpletable){
System.out.println(simpletable1.getAddress());
}
}
I fetched data but how can I update now. 我获取了数据,但我现在如何更新。 Is it possible to iterate through a loop and setAddress("US") 是否可以迭代循环和setAddress(“US”)
Since you are creating a standalone application, you must open a transaction first, then you can simply change the field values in your object and when the transaction is committed, the changes get flushed to the database automatically. 由于您要创建独立应用程序,因此必须首先打开事务,然后只需更改对象中的字段值,并且在提交事务时,更改将自动刷新到数据库。
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
try {
for(SimpleTable simpleTable : simpleTables){
simplaTable.setAddress(newAddress);
}
} finally {
tx.commit();
}
} catch (Exception e) {
// handle exceptions from transaction methods
}
--Edit-- - 编辑 -
An alternative to edit all records without having to first fetch them is to do a bulk update, still within a transaction, like this: 编辑所有记录而不必首先获取它们的替代方法是进行批量更新,仍然在事务中,如下所示:
entityManager.createQuery("UPDATE SimpleTable s " +
"SET s.address.state = ?1 " +
"WHERE s.address.country = ?2")
.setParameter(1, "FL")
.setParameter(2, "US")
.executeUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.