JPA:仅更新特定字段
2022-08-31 12:39:46
有没有办法使用Spring Data JPA中的方法仅更新实体对象的某些字段?save
例如,我有一个像这样的JPA实体:
@Entity
public class User {
@Id
private Long id;
@NotNull
private String login;
@Id
private String name;
// getter / setter
// ...
}
通过其 CRUD 存储库:
public interface UserRepository extends CrudRepository<User, Long> { }
在Spring MVC中,我有一个控制器来获取一个用于更新它的对象:User
@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);
// ...
}
我知道我可以使用加载用户,然后更改其名称并使用...但是,如果我有100个字段,并且我想更新其中的50个字段,则更改每个值可能会非常烦人。findOne
save
有没有办法告诉“保存对象时跳过所有空值”之类的东西?