Spring 启动 - 验证在 POST 上无法使用 DTO
Spring Boot - Validation not working on POST with DTO
我遇到了问题。
我尝试使用 @Valid 注释验证传递给我的 DTO 的数据,但没有结果。在堆栈跟踪中,数据通常插入到数据库中。
我预计至少有一个错误的请求。
起初我只在 POST 方法中进行测试。
控制器
@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);
}
堆栈跟踪
Hibernate: insert into user (id, birth_date, cpf, email, name) values (null, ?, ?, ?, ?)
我最终发现从我的 pom.xml 中删除依赖项解决了问题。
虽然我还没有把这个依赖引入到我的项目中。它引起了一些冲突,并且在堆栈跟踪中没有给我任何错误。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
我遇到了问题。 我尝试使用 @Valid 注释验证传递给我的 DTO 的数据,但没有结果。在堆栈跟踪中,数据通常插入到数据库中。 我预计至少有一个错误的请求。
起初我只在 POST 方法中进行测试。
控制器
@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);
}
堆栈跟踪
Hibernate: insert into user (id, birth_date, cpf, email, name) values (null, ?, ?, ?, ?)
我最终发现从我的 pom.xml 中删除依赖项解决了问题。
虽然我还没有把这个依赖引入到我的项目中。它引起了一些冲突,并且在堆栈跟踪中没有给我任何错误。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>