Issue
I have a RestController containing an HTTP endpoint to create a new user.
@RestController
public class UserController {
@PostMapping("/user")
public CompletableFuture<ResponseEntity<UserResponse>> createUser(
@Valid @RequestBody UserRequest userRequest) {
return CompletableFuture.completedFuture(
ResponseEntity.status(HttpStatus.ACCEPTED).body(userService.createUser(userRequest)));
}
}
My UserRequest model is as follows:
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_NULL)
@NoArgsConstructor
public class UserRequest {
// @NotNull
@NotEmpty private String name;
}
Now, every time I invoke the POST /user endpoint with a valid payload (e.g., { "name": "John" }
), I get the following error:
HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'name'"
In other words, the exception is thrown regardless of whether the "name" property was empty or not.
However, when I use the @NotNull
constraint instead, the exception is only thrown in the absence of the name property or { "name": null }
, as expected.
Am I misusing the @NotEmpty constraint?
Solution
Maven dependencies (in pom.xml) -
<!-- Java bean validation API - Spec -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- Hibernate validator - Bean validation API Implementation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.11.Final</version>
</dependency>
<!-- Verify validation annotations usage at compile time -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.0.11.Final</version>
</dependency>
In the user request model-
import javax.validation.constraints.NotEmpty;
@NotEmpty(message = "Name cannot be empty")
private String name;
Answered By - harsh tibrewal
Answer Checked By - Timothy Miller (JavaFixing Admin)