Is there a way for updating only some fields of an entity object using the method save
from Spring Data JPA?
For example I have a JPA entity like this:
@Entity
public class User {
@Id
private Long id;
@NotNull
private String login;
@Id
private String name;
// getter / setter
// ...
}
With its CRUD repo:
public interface UserRepository extends CrudRepository<User, Long> { }
In Spring MVC I have a controller that get an User
object for update it:
@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> updateUser(@RequestBody User user) {
// Assuming that user have its id and it is already stored in the database,
// and user.login is null since I don't want to change it,
// while user.name have the new value
// I would update only its name while the login value should keep the value
// in the database
userRepository.save(user);
// ...
}
I know that I could load the user using findOne
, then change its name and update it using save
... But if I have 100 fields and I want to update 50 of them it could be very annoying change each value..
Is there no way to tell something like "skip all null values when save the object"?
User
only hasnull
for the fields you don't want to save what you could do is the other way around, use the incomingUser
and update the fields you know haven't changed, then update that. – BrassiereEntityListener
or something like that, but I would strongly recommend against it as it will probably lead to more problems than it solves. – Brassiere