Java – what is the best way to update entities in JPA?

I am using JPA for some CRUD operations Do you want to update a correct method?

By updating the query or by finding the entitymanager? I have an employee object that I need to update Which is the right way? For convenience, the find method is good, so I use the find () method

Please guide me

Solution

Using executeupdate () on the query API is faster because it bypasses the persistence context However, bypassing the persistent context will cause the instance state in memory, and the actual value of the record in the DB will not be 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 refresh, the name in the DB will be updated to the new value, but the employee instance in memory will still maintain the original value You must call entitymanager Refresh (employee) can reload the updated name from DB to employee instance It sounds strange if your code still needs to refresh the operator worker instance after refreshing, but you forget to refresh the () employee instance because the employee instance still contains the original value

Typically, executeupdate () is used during batch updates because it is faster because it bypasses the persistence context

The correct way to update an entity is to simply set the properties to be updated through the setter and let JPA generate update SQL during refresh, rather than writing it manually

Employee employee= (Employee)entityManager.find(Employee.class,1);
   employee.setName("Updated Name");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>