DTOs: Separating API from Database

DTOs: Separating API from Database in Java: The quickest way to build an endpoint is to return your JPA entity directly.

Concept Explanation

The quickest way to build an endpoint is to return your JPA entity directly. It also creates three problems at once:

  1. Leaked fields — your User entity has a passwordHash, and now so does your JSON.
  2. A frozen schema — renaming a database column silently breaks every client.
  3. 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

  1. @JsonIgnore on the entity instead of using a DTO: It works until someone adds a field and forgets the annotation. Whitelisting beats blacklisting.
  2. One DTO for request and response: The client should never send id or createdAt, and should never receive password.
  3. Mapping inside the controller: Move it to a mapper so it is testable and reusable.
  4. 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

  1. The Hidden Field: Return an entity with a sensitive field, observe it in the JSON, then eliminate it with a response DTO.
  2. The Mapper Test: Unit-test toResponse with no Spring context — proof the mapping is plain Java.
  3. The Date Format: Make a LocalDateTime serialise as 2026-08-24 14:30 instead of an ISO timestamp.