更新 JPA 中实体的最佳方法是什么
我正在使用 JPA 进行一些 CRUD 操作。对于更新对象,正确的方法是什么?
通过update查询还是通过EntityManager
的find
方法?
我有一个需要更新的 Employee
对象。哪一个是正确的方法?
请指导我。
I am doing some CRUD operations using JPA. For updating an object which is the right way to do?
Through update query or through the find
method of EntityManager
?
I have one Employee
object I need to update. Which is the right way?
Please guide me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
Query
API 上使用executeUpdate()
速度更快,因为它绕过了持久上下文。但是,绕过持久上下文会导致内存中实例的状态与实际情况不同。数据库中该记录的值未同步。考虑以下示例:
刷新后,数据库中的名称更新为新值,但内存中的员工实例仍保留原始值。您必须调用
entityManager.refresh(employee)
来将更新后的名称从数据库重新加载到员工实例。如果您的代码在刷新后仍然需要操作员工实例,但您忘记刷新()员工实例,因为员工实例仍然包含原始值,这听起来很奇怪。通常,
executeUpdate()
用于批量更新过程,因为它会绕过持久上下文,速度更快更新实体的正确方法是您只需通过设置器设置要更新的属性并让 JPA 在刷新期间为您生成更新 SQL,而不是手动编写。
Using
executeUpdate()
on theQuery
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.Consider the following example :
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call
entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.Normally ,
executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent contextThe right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
这取决于您想要做什么,但正如您所说,使用 find() 获取实体引用,然后更新该实体是最简单的方法。
我不会担心各种方法的性能差异,除非您有强烈的迹象表明这确实很重要。
That depends on what you want to do, but as you said, getting an entity reference using
find()
and then just updating that entity is the easiest way to do that.I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.
这取决于要更新的实体数量,如果您有大量实体,则使用 JPA 查询更新语句会更好,因为您不必从数据库加载所有实体,如果您只想更新一个实体,则使用查找并更新就可以了。
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.