[java] What is the best way to update the entity in JPA

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.

This question is related to java jpa entitymanager

The answer is


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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jpa

No converter found capable of converting from type to type How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Deserialize Java 8 LocalDateTime with JacksonMapper Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed How to beautifully update a JPA entity in Spring Data? JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory How to return a custom object from a Spring Data JPA GROUP BY query How to find distinct rows with field in list using JPA and Spring? What is this spring.jpa.open-in-view=true property in Spring Boot? Spring Data JPA and Exists query

Examples related to entitymanager

What does EntityManager.flush do and why do I need to use it? JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory The EntityManager is closed What is the best way to update the entity in JPA Create JPA EntityManager without persistence.xml configuration file JPA EntityManager: Why use persist() over merge()?