在JPA中更新实体的最佳方法是什么 [英] What is the best way to update the entity in JPA
问题描述
我正在使用JPA进行一些CRUD操作。更新对象哪种方法正确?
I am doing some CRUD operations using JPA. For updating an object which is the right way to do?
通过更新查询或通过查找
方法
EntityManager
?$
我需要更新一个 Employee
对象。哪种方法正确?为了方便,查找
方法是好的,所以我使用 find()
方法。
Through update query or through find
method of EntityManager
?
I have one Employee
object I need to update. Which is the right way? For easiness, find
method is good, so I used the find()
method.
请指导我。
推荐答案
使用 executeUpdate()
在查询
API上更快,因为它绕过了持久化上下文。但是,绕过持久化上下文会导致内存中实例的状态和实际值数据库中该记录的数据未同步。
Using executeUpdate()
on the Query
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.
请考虑以下示例:
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
刷新后,DB中的名称将更新为新值,但内存中的员工实例仍保留原始值。您必须调用 entityManager.refresh(employee)
将更新后的名称从DB重新加载到员工实例。如果您的代码仍然存在,这听起来很奇怪在刷新后操作员工实例但是忘记刷新()员工实例,因为员工实例仍然包含原始值。
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.
通常, executeUpdate()
用于批量更新过程,因为它绕过持久化上下文更快
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
更新实体的正确方法是您只需通过setter设置要更新的属性,让JPA在刷新期间为您生成更新SQL,而不是手动编写。
The 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.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");
这篇关于在JPA中更新实体的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!