使用 JPA 更新多行
我想更新列 NAME 值为“PCNAME”的表的所有字段。 我要更新的表名称是 XYZ。我只想更新某些字段而不保留某些字段不变。
这将影响许多行,而不是单行,因为会有许多行 NAME='PCNAME' 我如何使用 JPA 来做到这一点。我有与此表关联的实体类。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以采用面向对象的方式或使用更新查询来完成此操作。
面向对象:
使用更新查询(未经测试):
显然,第二个版本性能更好。
You can either do it the object oriented way or using an update query.
Object oriented:
With Update Query (untested):
Obviously, the second version performs better.
Seanizer 的答案是正确的 (+1),批量更新将是对于这个用例来说确实很好。但您必须对批量更新操作采取一些预防措施。解释一下 JPA 规范:
因此,我的建议是至少增加版本列以避免与其他线程的并发问题:
并在单独的事务中或在加载任何 XYZ 之前执行它,如前所述。
参考
seanizer's answer is correct (+1) and a bulk update would be indeed nice for this use case. But you must take some precautions with bulk update operations. To paraphrase the JPA specification:
My suggestion would thus be to at least increment the version column to avoid concurrency problem with other threads:
And to perform it in a separate transaction or before loading any XYZ as previously explained.
References
从 Java Persistence 2.1 开始,您可以使用
CriteriaUpdate< /code>
使用 Criteria API 进行批量更新。
记住:
Since Java Persistence 2.1 you can use
CriteriaUpdate
to do bulk updates using the Criteria API.Keep in mind: