Controllers & DTOs, and why entities never leave the service
The request lifecycle in Spring MVC, @RestController mechanics, and why every project uses separate request/response DTOs instead of exposing entities.
The concept
Request lifecycle in Spring MVC
HTTP request
-> Tomcat thread
-> Servlet filter chain (CORS, security, JWT filter, rate limit, correlation id)
-> DispatcherServlet
-> HandlerMapping finds @GetMapping("/bookings/{id}")
-> HandlerInterceptors
-> Argument resolvers: @PathVariable, @RequestParam, @RequestBody (Jackson JSON -> object),
@AuthenticationPrincipal, Pageable
-> @Valid triggers Bean Validation
-> Your controller method -> service -> repository
-> Return value -> HttpMessageConverter (object -> JSON)
-> Exceptions -> @ControllerAdvice
What a DTO is
A Data Transfer Object is a shape designed for the API contract. An entity is a shape designed for the database. Keep them separate:
// Entity: persistence concerns
@Entity class User {
@Id UUID id; String email; String passwordHash;
@ManyToMany Set<Role> roles; boolean isActive; Instant createdAt;
}
// Request DTO: what a client may send
public record RegisterUserRequest(@NotBlank String name, @Email String email,
@Size(min = 8) String password) {}
// Response DTO: what a client may see
public record UserResponse(UUID id, String name, String email) {}
Reasons to separate them:
- Security. Returning the entity would leak
passwordHash. Accepting the entity as input allows mass assignment, e.g. a client sending"role":"ADMIN". - Stability. You can rename a column without breaking the API.
- Avoiding lazy-loading explosions. Jackson serialising an entity walks every relationship, which triggers N+1 queries,
LazyInitializationException, or infinite recursion. - Use-case shapes. A list view needs less data than a detail view.
In your projects
module/booking/dto · module/hostel/dtoHostel splits read models by use case: BookingSummaryDto (lists), HostelDetailsResponseDto (detail page) and RoomDisplayDto. Request DTOs are validated records like CreateBookingRequest.
module/account/web/dto/RM separates by operation, e.g. CreateAccountDto, UpdateAccountDto and AccountResponse. Create and update differ because some fields are immutable after creation.
controllers/CartController.javaStore’s controllers build ResponseEntity with correct status codes, but some carry @Transactional on the controller method (CartController.addItemToCart, UserController.registerUser). The transaction boundary should sit in the service, where the business operation lives (see the transactions lesson).
*/web/dto/*Dtos.javaOne file per module holds nested records, e.g. JournalDtos.CreateJournalRequest and JournalDtos.JournalResponse. It is compact and easy to find.
Alternatives
| Option | Trade-off |
|---|---|
| Separate DTOs (yours) | Safe and explicit, but more classes and mapping |
Expose entities + @JsonIgnore |
Quick, but leaks, breaks on schema change, and causes lazy-loading bugs |
| Spring Data projections (interfaces/records) | Query straight into a DTO shape; Hostel uses *FlatProjection for native queries |
@JsonView |
One class, several views; gets confusing |
| GraphQL | The client picks fields (bonus module) |
Related concepts you must know
@RestController=@Controller+@ResponseBody.- Jackson config. Date formats (ISO-8601),
@JsonInclude(NON_NULL)(Hostel’sApiResponse), unknown-property handling. Hostel and Store each have aJacksonConfig. @AuthenticationPrincipalinjects the logged-in user.- Thin controllers. Controllers translate HTTP to a use case and back. Business rules belong in services or the domain.
- Command/query separation. Hostel’s “Summary vs Detail” DTOs are a lightweight form of CQRS.