简体   繁体   中英

Spring Boot - Validation not working on POST with DTO

I'm having a problem. I try to validate the data passed to my DTO using the @Valid annotation and there is no result. In the stack trace the data is normally inserted in the database. I expected at least one bad request.

At first I'm testing only in the POST method.

Controller

    @PostMapping
    public ResponseEntity<UserResponse> createUser(@Valid @RequestBody UserForm dto) {
        User userToAdd = dto.dtoToUser();
        userService.createUser(userToAdd);
        return new ResponseEntity<>(UserResponse.convertToDto(userToAdd), HttpStatus.CREATED);

    }

DTO

public class UserForm {

    @NotBlank
    private String name;
    @CPF
    private String cpf;
    @Email
    private String email;
    @NotBlank
    private LocalDate birthDate;

    public UserForm(String name, String cpf, String email, LocalDate birthDate) {
        this.name = name;
        this.cpf = cpf;
        this.email = email;
        this.birthDate = birthDate;
    }

    public User dtoToUser() {
        return new User(this.name, this.email, this.cpf, this.birthDate);
    }

I ended up finding that removing a dependency from my pom.xml solved the problem.

Although I haven't imported this dependency into my project. It was causing some conflict and didn't give me any error in stacktrace.

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.1.Final</version>
        </dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM