Bird
Raised Fist0
Spring Bootframework~10 mins

DTO pattern for data transfer in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - DTO pattern for data transfer
Client sends request
Controller receives request
Controller uses DTO to receive/send data
Service processes data
Entity maps to DTO
DTO sent back to client
Data flows from client to controller using DTOs, processed by service, then entity data maps back to DTO for response.
Execution Sample
Spring Boot
public record UserDTO(String name, String email) {}

@RestController
public class UserController {
  @PostMapping("/user")
  public UserDTO createUser(@RequestBody UserDTO userDTO) {
    return userDTO;
  }
}
A simple Spring Boot controller receives a UserDTO, then returns it back as response.
Execution Table
StepActionInput DataDTO StateOutput/Response
1Client sends POST /user with JSON {"name":"Anna","email":"anna@example.com"}JSON {name: Anna, email: anna@example.com}UserDTO{name='Anna', email='anna@example.com'}No response yet
2Spring deserializes JSON to UserDTOJSONUserDTO{name='Anna', email='anna@example.com'}No response yet
3Controller method createUser called with UserDTOUserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'}No response yet
4Controller returns same UserDTO as responseUserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'} serialized to JSON
5Client receives JSON responseNo inputNo DTO state changeJSON {"name":"Anna","email":"anna@example.com"}
💡 Request handled, DTO used to transfer data cleanly between client and server
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
userDTOnullUserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'}UserDTO{name='Anna', email='anna@example.com'}
Key Moments - 2 Insights
Why do we use a DTO instead of directly using the entity class?
DTOs help separate internal entity structure from external data transfer, improving security and flexibility. See execution_table step 3 where controller uses DTO, not entity.
How does Spring convert JSON to DTO automatically?
Spring uses Jackson library to deserialize JSON into DTO fields before controller method runs, as shown in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of userDTO after step 2?
Anull
BEmpty DTO
CUserDTO{name='Anna', email='anna@example.com'}
DJSON string
💡 Hint
Check the 'DTO State' column at step 2 in execution_table
At which step does the controller method receive the DTO?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column describing controller method call
If the client sends extra fields in JSON not in DTO, what happens?
AExtra fields are ignored during deserialization
BDTO includes extra fields automatically
CSpring throws an error
DDTO fields become null
💡 Hint
Think about how Jackson handles unknown JSON properties when mapping to DTO
Concept Snapshot
DTO pattern in Spring Boot:
- Use DTO classes to transfer data between client and server
- Controller methods accept and return DTOs, not entities
- Spring auto-converts JSON to/from DTO using Jackson
- Keeps internal data safe and API clear
- Simple record or class can define DTO fields
Full Transcript
This visual trace shows how the DTO pattern works in Spring Boot. The client sends JSON data to the server. Spring converts this JSON into a DTO object before the controller method runs. The controller uses this DTO to process data and returns a DTO as response. This keeps the internal entity separate from external data transfer. The variable tracker shows the DTO object state stays consistent through the steps. Key moments clarify why DTOs are used and how Spring deserializes JSON. The quiz tests understanding of DTO state and flow. Overall, DTOs help keep data transfer clean and safe in Spring applications.

Practice

(1/5)
1. What is the main purpose of using a DTO (Data Transfer Object) in a Spring Boot application?
easy
A. To manage application configuration settings
B. To store data permanently in the database
C. To handle user authentication and authorization
D. To safely transfer only necessary data between different parts of the application

Solution

  1. Step 1: Understand the role of DTOs

    DTOs are simple objects designed to carry data between layers or parts of an application without exposing sensitive or unnecessary details.
  2. Step 2: Identify the correct purpose

    Unlike entities or configuration classes, DTOs focus on safe and clean data transfer, not storage or security management.
  3. Final Answer:

    To safely transfer only necessary data between different parts of the application -> Option D
  4. Quick Check:

    DTO purpose = safe data transfer [OK]
Hint: DTOs move data safely without exposing all details [OK]
Common Mistakes:
  • Confusing DTOs with database entities
  • Thinking DTOs handle security
  • Assuming DTOs store data permanently
2. Which of the following is the correct way to define a simple DTO class in Spring Boot using Java records?
easy
A. public record UserDTO(String name, String email) {}
B. public class UserDTO { private String name; private String email; }
C. public interface UserDTO { String getName(); String getEmail(); }
D. public enum UserDTO { NAME, EMAIL }

Solution

  1. Step 1: Recognize Java record syntax

    Java records provide a concise way to create immutable data carriers with automatic getters and constructors.
  2. Step 2: Match the correct syntax

    public record UserDTO(String name, String email) {} uses the correct record declaration with fields inside parentheses and empty body braces.
  3. Final Answer:

    public record UserDTO(String name, String email) {} -> Option A
  4. Quick Check:

    Java record syntax = public record UserDTO(String name, String email) {} [OK]
Hint: Java records use 'record Name(fields) {}' syntax [OK]
Common Mistakes:
  • Using class without constructors/getters
  • Confusing interface with DTO class
  • Using enum for data transfer
3. Given this Spring Boot code snippet, what will be the output when the getUserDTO() method is called?
public record UserDTO(String name, int age) {}

public UserDTO getUserDTO() {
    UserDTO user = new UserDTO("Alice", 30);
    return new UserDTO(user.name(), user.age() + 5);
}
medium
A. UserDTO[name=Alice, age=5]
B. UserDTO[name=Alice, age=35]
C. UserDTO[name=Alice, age=30]
D. Compilation error due to missing constructor

Solution

  1. Step 1: Understand record instantiation and methods

    The record UserDTO has fields name and age with automatic accessor methods name() and age().
  2. Step 2: Analyze the returned object

    The method creates a UserDTO with name "Alice" and age 30, then returns a new UserDTO with the same name and age increased by 5 (30 + 5 = 35).
  3. Final Answer:

    UserDTO[name=Alice, age=35] -> Option B
  4. Quick Check:

    Age incremented by 5 = 35 [OK]
Hint: Records have automatic getters like name() and age() [OK]
Common Mistakes:
  • Forgetting to add 5 to age
  • Confusing method calls with field access
  • Assuming default toString format
4. Identify the error in this DTO usage code snippet:
public record ProductDTO(String name, double price) {}

public ProductDTO createProduct() {
    ProductDTO product = new ProductDTO("Book");
    return product;
}
medium
A. Missing second argument for price in ProductDTO constructor
B. Records cannot be used as DTOs
C. Method createProduct should return void
D. ProductDTO fields must be private

Solution

  1. Step 1: Check record constructor parameters

    The ProductDTO record requires two parameters: a String name and a double price.
  2. Step 2: Identify constructor call mistake

    The constructor call provides only one argument "Book", missing the price argument, causing a compile-time error.
  3. Final Answer:

    Missing second argument for price in ProductDTO constructor -> Option A
  4. Quick Check:

    Constructor args must match record fields [OK]
Hint: Record constructors need all fields in order [OK]
Common Mistakes:
  • Passing fewer arguments than fields
  • Thinking records can't be DTOs
  • Ignoring method return types
5. You want to create a DTO that hides the user's password when sending data to the client. Given the entity:
public class User {
    private String username;
    private String password;
    private String email;
    // getters and setters
}

Which DTO definition best achieves this goal?
hard
A. public class UserDTO { private String password; }
B. public record UserDTO(String username, String password, String email) {}
C. public record UserDTO(String username, String email) {}
D. public record UserDTO(String password) {}

Solution

  1. Step 1: Understand the goal to hide password

    The DTO should exclude the password field to avoid exposing it to clients.
  2. Step 2: Choose DTO fields accordingly

    public record UserDTO(String username, String email) {} includes only username and email, omitting password, which meets the requirement.
  3. Final Answer:

    public record UserDTO(String username, String email) {} -> Option C
  4. Quick Check:

    Exclude sensitive fields in DTO [OK]
Hint: Exclude sensitive fields from DTO to hide them [OK]
Common Mistakes:
  • Including password in DTO fields
  • Using DTO with only password
  • Confusing entity with DTO