Post

Spring) Spring Boot DTO/Lombok/Validation

Spring) Spring Boot DTO/Lombok/Validation

This post was migrated from Tistory. You can find the original here.

DTO/Lombok

1
2
3
4
5
6
@Getter
public class UserSignUpDto {
    ...
    private boolean admin = false;
    ...
}

For a boolean field, @Getter generates isAdmin().
Boolean values conventionally start with is. e.g. OptionalType.isEmpty()/isPresent()

1
2
3
4
5
6
7
8
9
10
11
@Getter
@Setter
@ToString(callSuper = true)
public class PostUpdateDto extends PostUserDto {
    private Optional<String> title;
    private Optional<String> contents;

    public PostUpdateDto(String username, String password) {
        super(username, password);
    }
}
1
2
3
4
5
6
7
8
9
10
@AllArgsConstructor
@Getter
@Setter
@ToString
public class PostUserDto {
    @NotBlank
    private String username;
    @NotBlank
    private String password;
}

When inheriting, applying @ToString(callSuper = true) also prints the parent class’s fields.
e.g. PostUpdateDto(super=PostUserDto(username=choi0, password=abcd), title=Optional[hi2], contents=null)

@Getter/@Setter are unrelated to the parent class. You still need to write the constructor yourself.
As shown above, validation on the parent class works correctly even in this setup.

Validation

Add implementation 'org.springframework.boot:spring-boot-starter-validation' to gradle.

1
2
3
4
5
6
7
(controller)
@PatchMapping("/{postId}")
public PostResponseDto patchPost(@PathVariable Long postId, @Valid PostUpdateDto requestDto, BindingResult bindResult) {
        List<FieldError> fieldErrors = bindResult.getFieldErrors();
        if(fieldErrors.size() > 0) throw new IllegalArgumentException("Dto fail");
        ...
    }

A plain DTO could previously be assigned a null value. Once validation is applied to the DTO and declared on the controller, the request goes through validation and the result is returned via BindingResult.
If there are errors in the result, you can throw them and handle them with something like @ExceptionHandler(Error.class).

This post is licensed under CC BY-NC 4.0 by the author.