Bird
Raised Fist0
Spring Bootframework~10 mins

Why DTOs matter in Spring Boot - Visual Breakdown

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 - Why DTOs matter
Client sends request
Controller receives request
Controller uses DTO to capture input
Service processes data
Service returns entity
Controller converts entity to DTO
Controller sends DTO response to client
This flow shows how DTOs act as a middle layer between client and server, capturing input and shaping output safely.
Execution Sample
Spring Boot
public record UserDTO(String name, String email) {}

@PostMapping("/users")
public UserDTO createUser(@RequestBody UserDTO userDTO) {
    User user = userService.save(userDTO);
    return new UserDTO(user.getName(), user.getEmail());
}
This code receives user data as a DTO, saves it, and returns a DTO response, protecting internal data.
Execution Table
StepActionData StateResult
1Client sends JSON with name and email{}Request received with {name, email}
2Controller maps JSON to UserDTOUserDTO{name, email}DTO created with client data
3Service saves UserDTO as User entityUser{name, email, id, password}Entity saved with extra fields
4Controller converts User entity to UserDTOUserDTO{name, email}Sensitive fields excluded
5Controller sends UserDTO as JSON responseUserDTO{name, email}Client receives safe data
6EndN/AProcess complete
💡 Process ends after sending safe DTO response to client, hiding internal entity details.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
userDTOnull{name, email}{name, email}{name, email}{name, email}
userEntitynullnull{name, email, id, password}{name, email, id, password}{name, email, id, password}
Key Moments - 2 Insights
Why do we convert the entity back to a DTO before sending the response?
Because the entity may contain sensitive or internal data (like passwords or IDs) that should not be exposed to the client. The DTO only includes safe fields, as shown in step 4 of the execution_table.
Why not use the entity directly for input and output?
Using entities directly can expose internal structure and sensitive data, and can cause tight coupling between client and server. DTOs act as a safe, controlled data shape, as seen in steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what data does the controller receive at step 2?
ARaw JSON string
BUser entity with id and password
CUserDTO with name and email
DEmpty object
💡 Hint
Check the 'Data State' column at step 2 in the execution_table.
At which step does the service create the User entity with extra fields?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Data State' columns in the execution_table for step 3.
If we skipped converting the entity to a DTO before response, what risk increases?
AClient receives sensitive internal data
BClient gets incomplete data
CServer crashes
DNo data is sent
💡 Hint
Refer to the key_moments about why conversion back to DTO is important.
Concept Snapshot
DTOs (Data Transfer Objects) are simple objects used to carry data between processes.
In Spring Boot, controllers receive and send DTOs to protect internal entity details.
DTOs prevent exposing sensitive data like passwords or internal IDs.
They decouple client data format from server internal models.
Always convert entities to DTOs before sending responses.
Full Transcript
In Spring Boot applications, DTOs matter because they act as safe containers for data sent between client and server. When a client sends data, the controller maps it into a DTO, which only includes the fields the client should provide. The service layer converts this DTO into an entity that may have more fields like IDs or passwords. Before sending data back to the client, the controller converts the entity back into a DTO to exclude sensitive information. This process protects internal data and keeps client-server communication clear and secure.

Practice

(1/5)
1. Why do we use DTOs (Data Transfer Objects) in a Spring Boot application?
easy
A. To make the application slower by adding extra layers
B. To increase the size of data sent over the network
C. To replace the database entities completely
D. To carry only the data we want to share and hide internal details

Solution

  1. Step 1: Understand the purpose of DTOs

    DTOs are designed to carry only the necessary data between processes or layers, avoiding exposure of internal details.
  2. Step 2: Analyze the options

    To carry only the data we want to share and hide internal details correctly states the purpose of DTOs. The other options describe incorrect or harmful uses.
  3. Final Answer:

    To carry only the data we want to share and hide internal details -> Option D
  4. Quick Check:

    DTOs protect and simplify data transfer = D [OK]
Hint: DTOs share only needed data, hiding internals [OK]
Common Mistakes:
  • Thinking DTOs replace entities fully
  • Assuming DTOs increase data size
  • Believing DTOs slow down the app
2. Which of the following is the correct way to define a simple DTO class in Spring Boot?
easy
A. public class UserDTO { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
B. @Entity public class UserDTO { private String name; private int age; }
C. public interface UserDTO { String getName(); int getAge(); }
D. @Repository public class UserDTO { private String name; private int age; }

Solution

  1. Step 1: Identify correct DTO structure

    A DTO is a simple class with private fields and public getters/setters, without annotations like @Entity or @Repository.
  2. Step 2: Evaluate each option

    public class UserDTO { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } correctly defines a DTO class with fields and accessors. @Entity public class UserDTO { private String name; private int age; } wrongly uses @Entity, which is for database entities. public interface UserDTO { String getName(); int getAge(); } defines an interface, not a DTO class. @Repository public class UserDTO { private String name; private int age; } wrongly uses @Repository, which is for data access layers.
  3. Final Answer:

    public class UserDTO { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } -> Option A
  4. Quick Check:

    DTO = simple class with getters/setters = B [OK]
Hint: DTOs are plain classes with getters/setters, no @Entity [OK]
Common Mistakes:
  • Adding @Entity annotation to DTO
  • Using interfaces instead of classes for DTO
  • Marking DTO as @Repository
3. Given this Spring Boot controller method, what will be the output JSON when calling /user?
@GetMapping("/user")
public UserDTO getUser() {
    UserDTO dto = new UserDTO();
    dto.setName("Alice");
    dto.setAge(30);
    return dto;
}
medium
A. {"name":"Alice"}
B. {"UserDTO":{"name":"Alice","age":30}}
C. {"name":"Alice","age":30}
D. Error: Cannot serialize UserDTO

Solution

  1. Step 1: Understand default JSON serialization in Spring Boot

    Spring Boot uses Jackson to convert returned objects to JSON, serializing all public getters by default.
  2. Step 2: Analyze the returned UserDTO object

    UserDTO has name and age fields with getters, so JSON will include both as simple key-value pairs.
  3. Final Answer:

    {"name":"Alice","age":30} -> Option C
  4. Quick Check:

    DTO fields serialize as JSON keys = A [OK]
Hint: Returned DTO converts to JSON with all getters [OK]
Common Mistakes:
  • Expecting nested JSON with class name
  • Assuming partial fields serialize
  • Thinking serialization causes error
4. What is wrong with this DTO class that causes a runtime error when Spring Boot tries to deserialize it?
public class ProductDTO {
    private String name;
    private int price;
    public ProductDTO(String name, int price) {
        this.name = name;
        this.price = price;
    }
}
medium
A. Fields should be public, not private
B. Missing default no-argument constructor
C. Constructor parameters should be annotated with @Autowired
D. Class should be annotated with @Entity

Solution

  1. Step 1: Identify deserialization requirements

    Jackson requires a default no-argument constructor to create an instance before setting fields via setters or reflection.
  2. Step 2: Check the DTO class

    This class only has a parameterized constructor and no default constructor, causing Jackson to fail during deserialization.
  3. Final Answer:

    Missing default no-argument constructor -> Option B
  4. Quick Check:

    Jackson needs no-arg constructor = A [OK]
Hint: DTOs need no-arg constructor for JSON serialization [OK]
Common Mistakes:
  • Thinking fields must be public
  • Adding @Autowired to constructor parameters
  • Confusing DTO with entity needing @Entity
5. You have an entity class User with many fields, but you want to expose only id and email in your API response. How should you use a DTO to achieve this cleanly?
hard
A. Create a UserDTO with only id and email fields, map User to UserDTO before returning
B. Return the User entity directly and ignore unwanted fields in the frontend
C. Add @JsonIgnore to all unwanted fields in the User entity
D. Use the User entity but rename unwanted fields to empty strings

Solution

  1. Step 1: Understand data exposure risks

    Returning the full User entity exposes all fields, risking sensitive data leaks.
  2. Step 2: Use DTO to control data

    Creating a UserDTO with only id and email fields and mapping User to UserDTO ensures only desired data is sent.
  3. Step 3: Evaluate other options

    Return the User entity directly and ignore unwanted fields in the frontend risks exposing all data. Add @JsonIgnore to all unwanted fields in the User entity mixes entity with serialization concerns and can be error-prone. Use the User entity but rename unwanted fields to empty strings is a bad practice and confusing.
  4. Final Answer:

    Create a UserDTO with only id and email fields, map User to UserDTO before returning -> Option A
  5. Quick Check:

    DTOs control exposed data = C [OK]
Hint: Use DTO to expose only needed fields safely [OK]
Common Mistakes:
  • Returning full entity directly
  • Using @JsonIgnore on entity fields
  • Modifying entity fields to hide data