Introduction
DTOs help move only the needed data between parts of an app. They keep things simple and safe.
Jump into concepts and practice - no test required
DTOs help move only the needed data between parts of an app. They keep things simple and safe.
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.
public record UserDTO(String name, String email) {}public class ProductDTO { private String id; private String title; private double price; // getters and setters }
This Spring Boot controller returns a UserDTO with only name and email. It hides the password field from the client.
package com.example.demo.dto;
public record UserDTO(String name, String email) {}
package com.example.demo.controller;
import com.example.demo.dto.UserDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user")
public UserDTO getUser() {
// Imagine this data comes from a database entity
String fullName = "Alice Johnson";
String email = "alice@example.com";
String password = "secret"; // We don't want to send this
// We create a DTO with only the safe data
return new UserDTO(fullName, email);
}
}DTOs improve security by not exposing sensitive fields.
They make your API responses smaller and faster.
Using records for DTOs reduces boilerplate code.
DTOs carry only the data you want to share.
They protect your app by hiding internal details.
DTOs keep your code clean and easy to maintain.
/user?
@GetMapping("/user")
public UserDTO getUser() {
UserDTO dto = new UserDTO();
dto.setName("Alice");
dto.setAge(30);
return dto;
}public class ProductDTO {
private String name;
private int price;
public ProductDTO(String name, int price) {
this.name = name;
this.price = price;
}
}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?