The DTO pattern helps move data between parts of an app clearly and simply. It keeps data organized and safe when sending it around.
DTO pattern for data transfer in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
public class UserDTO { private String name; private String email; // Constructor public UserDTO(String name, String email) { this.name = name; this.email = email; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
A DTO is a simple class with only fields and getters/setters.
It does not contain business logic or database code.
Examples
Spring Boot
public record UserDTO(String name, String email) {}Spring Boot
public class ProductDTO {
private String productName;
private double price;
// Constructors, getters, setters
}Sample Program
This example shows a User model with sensitive data like password. The UserDTO only carries name and email to safely transfer data without exposing the password.
Spring Boot
package com.example.demo.dto;
public record UserDTO(String name, String email) {}
package com.example.demo.model;
public class User {
private String name;
private String email;
private String password; // sensitive data
public User(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
public String getName() { return name; }
public String getEmail() { return email; }
public String getPassword() { return password; }
}
package com.example.demo.service;
import com.example.demo.dto.UserDTO;
import com.example.demo.model.User;
public class UserService {
public UserDTO convertToDTO(User user) {
return new UserDTO(user.getName(), user.getEmail());
}
}
package com.example.demo;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.dto.UserDTO;
public class DemoApplication {
public static void main(String[] args) {
User user = new User("Alice", "alice@example.com", "secret123");
UserService service = new UserService();
UserDTO dto = service.convertToDTO(user);
System.out.println("Name: " + dto.name());
System.out.println("Email: " + dto.email());
}
}Important Notes
DTOs help keep your app secure by not exposing sensitive fields.
They make your API responses cleaner and easier to maintain.
Use Java records for simple, immutable DTOs if your Java version supports it.
Summary
DTOs are simple objects to move data safely between app parts.
They hide sensitive or unnecessary data from outside users.
Using DTOs makes your code cleaner and easier to change later.
Practice
1. What is the main purpose of using a
DTO (Data Transfer Object) in a Spring Boot application?easy
Solution
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.Step 2: Identify the correct purpose
Unlike entities or configuration classes, DTOs focus on safe and clean data transfer, not storage or security management.Final Answer:
To safely transfer only necessary data between different parts of the application -> Option DQuick 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
Solution
Step 1: Recognize Java record syntax
Java records provide a concise way to create immutable data carriers with automatic getters and constructors.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.Final Answer:
public record UserDTO(String name, String email) {} -> Option AQuick 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
Solution
Step 1: Understand record instantiation and methods
The record UserDTO has fields name and age with automatic accessor methods name() and age().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).Final Answer:
UserDTO[name=Alice, age=35] -> Option BQuick 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
Solution
Step 1: Check record constructor parameters
The ProductDTO record requires two parameters: a String name and a double price.Step 2: Identify constructor call mistake
The constructor call provides only one argument "Book", missing the price argument, causing a compile-time error.Final Answer:
Missing second argument for price in ProductDTO constructor -> Option AQuick 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:
Which DTO definition best achieves this goal?
public class User {
private String username;
private String password;
private String email;
// getters and setters
}Which DTO definition best achieves this goal?
hard
Solution
Step 1: Understand the goal to hide password
The DTO should exclude the password field to avoid exposing it to clients.Step 2: Choose DTO fields accordingly
public record UserDTO(String username, String email) {} includes only username and email, omitting password, which meets the requirement.Final Answer:
public record UserDTO(String username, String email) {} -> Option CQuick 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
