@NotNull. What is the expected behavior if the client sends a null value for that field?public class UserDTO { @NotNull private String username; // getters and setters } @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody UserDTO userDTO) { return ResponseEntity.ok("User created"); }
When a DTO field is annotated with @NotNull and the client sends null, Spring Boot's validation mechanism triggers a validation error. This causes the framework to return a 400 Bad Request response with details about the validation failure.
public class ProductDTO { // field here @Size(min = 5, max = 10) private String code; // getters and setters }
The @Size annotation from javax.validation.constraints is used to validate the length of strings, collections, or arrays. It requires both min and max attributes to set length boundaries.
public class LoginDTO { @NotNull private String password; // getters and setters }
The @NotNull annotation only ensures the value is not null. It does not check if a string is empty. To validate non-empty strings, @NotBlank or @NotEmpty should be used.
@Min(18). If the client sends 16, what validation error message is generated by default?public class AgeDTO { @Min(18) private int age; // getters and setters }
The default message for @Min is must be greater than or equal to {value}. So for 18, it becomes must be greater than or equal to 18.
Using DTOs for validation helps keep the internal entity model separate from external input. It allows different validation rules for different API endpoints and prevents exposing sensitive or unnecessary entity details.