I am new to spring-boot I'm trying to add validation to my DTO class like below.
import javax.validation.constraints.NotBlank;
@Getter
@Setter
public class EmployeeDto {
private Long id;
@NotBlank(message = "Employee first name is required")
private String firstName;
private String lastName;
@NotBlank(message = "EmployeeNUM is required")
private String employeeNum;
}
Below is my REST endpoint to save employee.
import javax.validation.Valid;
@PostMapping("/employee")
public ResponseEntity<?> addEmployee(@Valid @RequestBody EmployeeDto employeeDto) throws ClassNotFoundException {
return ResponseEntity.ok(employeeService.saveEmployee(deptId,employeeDto));
}
I create a Validation class like below to validate the DTO fields.
@ControllerAdvice
@RestController
public class Validation {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}
expected output is
{ "firstName":"Employee first name is required", "employeeNum":"EmployeeNUM is required" }
But I'm getting only the 400 bad request when hit the endpoint through postman. What is the issue with my code? How to fix and get the expected output as mentioned above?