Java – spring data JPA update method
I'm still looking for an update method in spring's data JPA to update a given object that persists in a relational database I only found a solution. I had to specify an update query through the @ query annotation (compared 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);
To build a query, I also have to pass a single parameter instead of the entire object But that's what I want to do (pass the whole object)
So what I want to find is this method:
public void update(Object obj);
Can you build such an update method based on spring data JPA? How must it be annotated?
thank you!
Solution
If the goal is to modify the entity, no update method is required You can obtain an object from the database, modify it, and JPA automatically saves it:
User u = repository.findOne(id); u.setFirstName("new first name"); u.setLastName("new last name");
If you have a separate entity and want to merge it, use the save () method of crudrepository:
User attachedUser = repository.save(detachedUser);