Concept Explanation
The quickest way to build an endpoint is to return your JPA entity directly. It also creates three problems at once:
- Leaked fields — your
Userentity has apasswordHash, and now so does your JSON. - A frozen schema — renaming a database column silently breaks every client.
- Accidental lazy loading — Jackson touches a lazy collection during serialisation and fires surprise queries.
A DTO (Data Transfer Object) is a small class that exists purely to describe what crosses the wire.
Two DTOs Per Resource
// What the client may send
public record CreateUserRequest(
@NotBlank String username,
@Email String email,
@Size(min = 8) String password) { }
// What the client receives — note: no password field at all
public record UserResponse(
Long id,
String username,
String email,
LocalDateTime createdAt) { }
Records are ideal here: immutable, concise, and equals/hashCode come free.
Mapping
@Component
public class UserMapper {
public User toEntity(CreateUserRequest req, String hashedPassword) {
User u = new User();
u.setUsername(req.username());
u.setEmail(req.email());
u.setPasswordHash(hashedPassword);
return u;
}
public UserResponse toResponse(User u) {
return new UserResponse(u.getId(), u.getUsername(),
u.getEmail(), u.getCreatedAt());
}
}
The controller stays thin:
@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public UserResponse register(@Valid @RequestBody CreateUserRequest req) {
return mapper.toResponse(service.register(req));
}
Shaping the JSON
public record OrderResponse(
Long id,
@JsonFormat(pattern = "yyyy-MM-dd")
LocalDate placedOn,
@JsonInclude(JsonInclude.Include.NON_NULL) // omit when null
String note) { }
Handy global settings:
spring.jackson.default-property-inclusion=non_null
spring.jackson.serialization.write-dates-as-timestamps=false
Common Mistakes
@JsonIgnoreon the entity instead of using a DTO: It works until someone adds a field and forgets the annotation. Whitelisting beats blacklisting.- One DTO for request and response: The client should never send
idorcreatedAt, and should never receivepassword. - Mapping inside the controller: Move it to a mapper so it is testable and reusable.
- Returning entities "just for now": It never gets cleaned up, and one day the password hash ships.
Best Practices
- Records for DTOs: Immutable by construction.
- Separate request and response types, even when they start out nearly identical.
- Never expose internal ids or enums you may want to rename — map them deliberately.
Practice Exercises
- The Hidden Field: Return an entity with a sensitive field, observe it in the JSON, then eliminate it with a response DTO.
- The Mapper Test: Unit-test
toResponsewith no Spring context — proof the mapping is plain Java. - The Date Format: Make a
LocalDateTimeserialise as2026-08-24 14:30instead of an ISO timestamp.