1

I have UserDto.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "UserDto", description = " DTO User ")
public class UserDto {

    private Long userId;
    private String firstName;
    private String lastName;
    private LocalDate dateOfBirth;
    private String education;
    private String aboutMe;

I need to create update method.That's what I have now.

@PatchMapping("/{user}/edit")
    public ResponseEntity<String> update(@RequestBody UserDto userDto, @PathVariable long id) {
        Optional<User> optionalUser = userService.getById(id);
        if (!optionalUser.isPresent()) {
            return ResponseEntity
                    .badRequest()
                    .body("Пользователь не найден");
        }
        User user = optionalUser.get();
        userService.update(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

How can I use Dto to partial update user data? I assume I need a converter. Thanks!

  • Basically you'd just have to write some simple code like this: `if (userDto.getFirstName() != null) user.setFirstName(userDto.getFirstName());` – slauth Jul 28 '21 at 11:47
  • @slauth for all params?... – Vladislav Sedov Jul 28 '21 at 11:49
  • Yes. If you have plenty of them you could consider using a bean mapping framework like [MapStruct](https://mapstruct.org/). – slauth Jul 28 '21 at 12:06
  • The answers for https://stackoverflow.com/questions/1301697/helper-in-order-to-copy-non-null-properties-from-object-to-another discuss different ways to use common libraries to copy only non null properties. – Ralph Jul 28 '21 at 14:40

1 Answers1

0

You must create a constructor in Entity class and transform fields from dto to entity

DimasG
  • 27
  • 3