Issue
I'm still looking for a update method in Spring's Data JPA to update a given Object persited in a relational database. I only found solutions in which I'm forced to specify some kind of UPDATE queries via @Query annotation (in comparison with @Modifying), for example:
@Modifying
@Query("UPDATE User u SET u.firstname = ?1, u.lastname = ?2 WHERE u.id = ?3")
public void update(String firstname, String lastname, int id);
For building the Query, I also have to pass single parameters instead of whole Objects. But that's exactly what I want to do (passing whole Objects).
So, what I'm trying to find is a method like this:
public void update(Object obj);
Is it possible to build such a update method based on Spring Data JPA? How must it be annotated?
Thank you!
Solution
If the goal is to modify an entity, you don't need any update method. You get the object from the database, modify it, and JPA saves it automatically:
User u = repository.findOne(id);
u.setFirstName("new first name");
u.setLastName("new last name");
If you have a detached entity and want to merge it, then use the save()
method of CrudRepository
:
User attachedUser = repository.save(detachedUser);
Answered By - JB Nizet