What is a DTO(Data Transfer Object) and Why Use Them?
Let’s say you have two entity classes in your Spring Boot app:
class Account {
Long id;
String type;
Double balance;
Customer customer;
}
class Customer {
Long id;
String name;
String email;
}
Now the client says:
"We need account details along with the customer name and email in a single response."
You might think of modifying your entity to add/expose fields, but don’t do that.
Why NOT modify entities?
Entities are tied to your DB structure, not your API.
Entities often have lazy-loaded relationships, which can cause LazyInitializationException.
You end up coupling your DB design to frontend needs, which is fragile and messy.
What to do instead? Use a DTO (Data Transfer Object):
class AccountCustomerDTO {
Long accountId;
String accountType;
Double balance;
String customerName;
String customerEmail;
}
Now, your controller also becomes clean and client-friendly.
Benefits of DTOs:
Clean separation between DB model and API contract
Avoids exposing unnecessary or risky data
Easier to customize response formats
Plays well with versioning and frontend-specific needs
Works smoothly with tools like MapStruct or ModelMapper
DTOs are like wrappers ,they carry just what the client needs, nothing more.