使用JPA更新多行 [英] updating multiple rows using JPA
本文介绍了使用JPA更新多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更新一个具有colum NAME值为'PCNAME'的表的所有字段。
我要更新的表名是XYZ。我想只更新一些字段而不保持一些不变。
I want to update all fields of a table that has value of colum NAME as 'PCNAME'. The table name which i want to update is XYZ.I want to update only some fields and not keep some unchanged.
这会影响很多行而不是单行,因为会有很多行,其中NAME ='PCNAME'
我怎样才能使用JPA.I有与此表关联的实体类。
This will affect many rows and not a single row as there will be many rows with NAME='PCNAME' How can i do it using JPA.I have entity class associated with this table.
推荐答案
您可以采用面向对象的方式或使用更新查询。
You can either do it the object oriented way or using an update query.
面向对象:
public void setNameOfAllEntities(String newname){
List<MyEntity> items =
entityManager.createQuery("from MyEntity", MyEntity.class)
.getResultList();
for(MyEntity entity : items){
entity.setName(newname);
}
}
使用Update Query(未经测试):
public void setNameOfAllEntities(final String newname){
final int changes =
entityManager.createQuery("update MyEntity set name = :name")
.setParameter("name", newname)
.executeUpdate();
System.out.println(changes + " rows changed");
}
显然,第二个版本表现更好。
Obviously, the second version performs better.
这篇关于使用JPA更新多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文