BBackend CourseLeroy Labs
0/0
Search the course

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.

● beginnerSpring-Boot-StoreHostel-Web-AppReport-Manager-2SperoTek (in dev)

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
Spring MVC request lifecycleAn HTTP request passes the servlet filter chain, then the DispatcherServlet, then the controller, service and repository. The response goes back through message converters. Exceptions are turned into JSON by ControllerAdvice.HTTP requestTomcat threadFilter chainCORS · JWT · rate limitcorrelation id · tenantDispatcherServlethandler mapping@RestController@RequestBody (JSON → DTO)@Valid · @PreAuthorize@Service@Transactional business rulesRepository → PostgreSQLHikari connection@RestControllerAdviceexception → ApiError JSON (4xx/5xx)HTTP responseDTO → JSON via Jacksonthrows
Filters run before Spring MVC sees the request, which is why errors thrown there must write their own JSON.

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:

  1. Security. Returning the entity would leak passwordHash. Accepting the entity as input allows mass assignment, e.g. a client sending "role":"ADMIN".
  2. Stability. You can rename a column without breaking the API.
  3. Avoiding lazy-loading explosions. Jackson serialising an entity walks every relationship, which triggers N+1 queries, LazyInitializationException, or infinite recursion.
  4. Use-case shapes. A list view needs less data than a detail view.

In your projects

Hostel-Web-Appmodule/booking/dto · module/hostel/dto

Hostel splits read models by use case: BookingSummaryDto (lists), HostelDetailsResponseDto (detail page) and RoomDisplayDto. Request DTOs are validated records like CreateBookingRequest.

Report-Manager-2module/account/web/dto/

RM separates by operation, e.g. CreateAccountDto, UpdateAccountDto and AccountResponse. Create and update differ because some fields are immutable after creation.

Spring-Boot-Storecontrollers/CartController.java

Store’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).

SperoTek (in dev)*/web/dto/*Dtos.java

One 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)
  • @RestController = @Controller + @ResponseBody.
  • Jackson config. Date formats (ISO-8601), @JsonInclude(NON_NULL) (Hostel’s ApiResponse), unknown-property handling. Hostel and Store each have a JacksonConfig.
  • @AuthenticationPrincipal injects 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.

Check yourself

1. Which risk is NOT solved by separate DTOs?
2. Where should @Transactional live?