Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to update the entity in JPA

Tags:

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.

like image 760
user414967 Avatar asked Nov 29 '11 08:11

user414967


2 Answers

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"); 
like image 157
Ken Chan Avatar answered Oct 13 '22 00:10

Ken Chan


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.

like image 44
Thomas Avatar answered Oct 12 '22 22:10

Thomas