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.
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.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1); entityManager .createQuery("update Employee set name = \'xxxx\' where id=1") .executeUpdate();
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 context
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With