Sub topic 2
Using Records as Request and Response Bodies
Assume Java 17+, Spring Boot REST controllers, JSON, and basic HTTP knowledge. A data transfer object (DTO) is a type that carries data across an application boundary. Keep DTOs separate from JPA entities so API fields do not expose persistence details or change accidentally when the database model changes.
Request and response records
A Java record is a compact class for data that should have a fixed shape. Its components become private final fields, accessors, a constructor, equals, hashCode, and toString.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@Min(18) int age) {
}
public record UserResponse(Long id, String name, String email) {
}Jackson recognizes record components as JSON properties. It can deserialize a request such as {"name":"Ada","email":"[email protected]","age":36} and serialize a UserResponse with the same component names.
Validating records with Bean Validation
Bean Validation checks values against constraints such as @NotBlank, @Email, and @Min. Put constraints on record components, then add @Valid to the request body.
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
class UserController {
private final UserService service;
UserController(UserService service) {
this.service = service;
}
@PostMapping
ResponseEntity<UserResponse> create(
@Valid @RequestBody CreateUserRequest request) {
UserResponse created = service.create(request);
return ResponseEntity.created(
URI.create("/users/" + created.id())).body(created);
}
}Spring rejects invalid input before the service runs, normally with an HTTP 400 response. Validation does not replace business rules such as checking whether an email is already registered.
Normalizing state in compact constructors
A compact canonical constructor runs when the record is created. Use it for local normalization or invariants that must hold for every instance.
public record LoginRequest(String email, String password) {
public LoginRequest {
email = email == null ? null : email.strip().toLowerCase();
if (password != null && password.length() < 12) {
throw new IllegalArgumentException("Password is too short");
}
}
}Avoid putting database lookups or other application logic in a record constructor. Also remember that normalization does not replace Bean Validation.
Exercise
Where should @Valid be placed when a controller receives a record request?
Show answer
Place it on the parameter with @RequestBody, as in @Valid @RequestBody CreateUserRequest request.