如何从表单中只更新选定的记录?



主要问题是,如何从表单中更新几个选定的字段。我想给用户选择他们想要更新的字段。例如,我有一个表单类:

public class UserRegistrationform {
private Integer userId;
@NotNull
private String name;
@NotNull
private String surname;
@Email
@NotNull
private String email;
@NotNull
private Integer genderId;
@NotNull
private Integer groupId;
@NotNull
private List<ContactInfoDto> contactsInfo;
@NotNull
private String userSecretkey;
@NotNull
private String password;
@NotNull   
private boolean enabled;
@NotNull    
private boolean resetPassword;

之后,我在@EntityUser中设置字段,例如,如果用户只想更改他们的名字和姓氏,我想从现有的User中获取其余的字段,通过findById()方法,然后更改几个字段并将更改的对象保存到数据库中。

@BeshambherChaukhwan ok,也许会更容易,我将使用示例,所以我有一个控制器当它的方法:

@PostMapping(value = "{id}/updateuser")
public ResponseDTO updateUser(@PathVariable int id, @RequestBody UserRegistrationform userForm, BindingResult bindingResult) {
User user = userRepository.findById(id);
if (user == null) {
return ResponseDTO.of(Messages.Error_UserNotFound_MSG.getMessage(), ErrorCodes.NOT_FOUND);
} else if (bindingResult.hasErrors()) {
return ResponseDTO.of(bindingResult.getAllErrors().toString(), ErrorCodes.INVALID_FIELDS);
}
user.setName(userForm.getName);
user.setSurname(userForm.getSurname);
user.setEmail(userForm.getEmail);
.
.
.
userRepository.save(user);
return ResponseDTO.of(Messages.SUCCESS_Update_MSG.getMessage());
}

问题是,就像你注意到的形式有人错过了几个字段,我将通过空值更新右字段

最新更新