Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA Update Method

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!

like image 785
MaxWell Avatar asked Aug 30 '15 10:08

MaxWell


People also ask

How do I update JPA Spring data?

ALTER TABLE customer ADD UNIQUE (email); Refactor save() method logic so that it checks if an entry exists in the database. If it does, update the existing entry. Otherwise, create a new one and insert it into the database.

Which method is used for update operation in JPA?

Using the @Modifying Annotation As we can see, this method returns an integer. It's a feature of Spring Data JPA @Modifying queries that provides us with the number of updated entities.

How do I update entity in JPA?

In this example you will learn how to update an entity object in JPA. We use the EntityManager. merge() method to update an entity. This method takes the entity to be saved as the parameter and return the merged entity back as the result.

Does JPA update saveAll?

yes you can mix both new and existing entities in the passes list. One strange issue with this is that saveAll can't accurately determine whether the entity is new or not. This leads to duplication of records.


1 Answers

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);
like image 95
JB Nizet Avatar answered Oct 23 '22 21:10

JB Nizet