How to update only chosen records from form?

Viewed 81

The main question is, how to update just a few chosen fields from our form. I would like to give user choice which fields they want to update. For example, I have the form class:

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;

After that I'm setting fields in @Entity class User, and for example, if user want to change just their name and surname, I want to take the rest of the fields from the existing User, by findById() method and after that change a few fields and save the changed object to the database.

1 Answers

@BeshambherChaukhwan ok, maybe will be easier where I will use example, so I have a controller when is method:

    @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());
        }

The problem is, like you noticed when in form someone miss few fields, and I will update right fields by null values

Related