Data Transfer Objects
Data Transfer Objects
What is a DTO?
A Data Transfer Object (DTO) is a plain Java class used to transfer data between different
layers of an application without exposing internal business logic. DTOs do not contain
business logic—they only hold data.
Let’s consider a User Management System where we fetch user data but don’t expose
internal system fields.
class UserEntity {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
// Getters
public Long getId() { return id; }
class UserDTO {
this.username = username;
this.email = email;
// Getters
🔹 Why?
class UserMapper {
DTOs are commonly used in Spring Boot REST APIs to send responses.
Controller Example
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
@GetMapping("/{id}")
return UserMapper.toDTO(user);
"username": "JohnDoe",
"email": "[email protected]"
🔹 Why?
Password is hidden—it is NOT included in the response.
import java.util.List;
import java.util.stream.Collectors;
class UserService {
);
return users.stream().map(UserMapper::toDTO).collect(Collectors.toList());
In Spring Boot + JPA, we can use DTOs for optimized database queries.
}
🔹 Why?
Improves performance.
In APIs, we use:
Example
class UserRequestDTO {
class UserResponseDTO {
9. Summary
✔ Use DTOs to:
🚀 Want me to generate a full Spring Boot project with DTOs? Let me know! 😊