DTO (Data Transfer Object) Pattern in Java
Learn DTO Pattern in Java with Spring Boot, REST APIs, entity vs DTO, MapStruct, ModelMapper, microservices communication, enterprise architecture, code examples, and interview questions.
What You Will Learn
- What is DTO Pattern?
- Why DTO is Needed
- Entity vs DTO
- Request DTO
- Response DTO
- Spring Boot DTO Example
- MapStruct & ModelMapper
- Microservices Communication
- Enterprise Use Cases
- Benefits and Limitations
- Interview Questions
Introduction
Modern enterprise applications exchange data between:
Client
Controller
Service
Database
External Systems
Example Customer Entity:
@Entity
public class Customer {
private Long id;
private String name;
private String email;
private String password;
private String ssn;
}
Should we return this directly?
return customer;
Problem:
Password Exposed
SSN Exposed
Internal Fields Exposed
Security Risk
DTO Pattern solves this problem.
What is DTO?
DTO stands for:
Data Transfer Object
A DTO is an object used to transfer data between layers without exposing internal domain objects.
Purpose of DTO
Primary Goal:
Transfer Data Safely
Between Layers
Real World Analogy
Think about a Bank Account.
Database contains:
Account Number
Balance
PIN
Internal Notes
Audit Data
Customer sees:
Account Number
Balance
Not everything is exposed.
DTO acts like a filtered view.
Problem Without DTO
flowchart LR
A[Client]
B[Controller]
C[Entity]
D[Database]
A --> B
B --> C
C --> D
Entity directly exposed.
Solution With DTO
flowchart LR
A[Client]
B[Controller]
C[DTO]
D[Entity]
E[Database]
A --> B
B --> C
C --> D
D --> E
DTO protects internal model.
DTO Architecture
flowchart LR
A[Client]
B[Controller]
C[DTO]
D[Service]
E[Entity]
F[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
Why DTO is Important
Without DTO:
return customerEntity;
Problems:
Security Issues
Large Payloads
Tight Coupling
Versioning Problems
Entity Example
@Entity
public class Customer {
private Long id;
private String name;
private String email;
private String password;
private String ssn;
}
DTO Example
public class CustomerDTO {
private Long id;
private String name;
private String email;
}
Sensitive fields removed.
Entity vs DTO
| Feature | Entity | DTO |
|---|---|---|
| Database Mapping | Yes | No |
| Business Logic | Yes | No |
| Transfer Data | No | Yes |
| API Response | No | Yes |
Request DTO
Used for incoming requests.
Example:
public class CreateCustomerRequest {
private String name;
private String email;
}
Response DTO
Used for outgoing responses.
public class CustomerResponse {
private Long id;
private String name;
private String email;
}
Request Response Flow
flowchart LR
A[Client]
B[Request DTO]
C[Controller]
D[Service]
E[Entity]
F[Response DTO]
A --> B
B --> C
C --> D
D --> E
E --> F
Spring Boot Example
Entity
@Entity
public class Customer {
@Id
private Long id;
private String name;
private String email;
private String password;
}
DTO
public class CustomerDTO {
private Long id;
private String name;
private String email;
}
Service Mapping
public CustomerDTO getCustomer(
Long id) {
Customer customer =
repository.findById(id)
.orElseThrow();
CustomerDTO dto =
new CustomerDTO();
dto.setId(customer.getId());
dto.setName(customer.getName());
dto.setEmail(customer.getEmail());
return dto;
}
Controller
@GetMapping("/{id}")
public CustomerDTO getCustomer(
@PathVariable Long id) {
return service.getCustomer(id);
}
JSON Response
{
"id": 1,
"name": "John",
"email": "[email protected]"
}
Password hidden.
DTO Mapping Flow
flowchart LR
A[Entity]
B[Mapper]
C[DTO]
A --> B
B --> C
Manual Mapping
dto.setName(
entity.getName());
dto.setEmail(
entity.getEmail());
Works but repetitive.
ModelMapper Example
ModelMapper mapper =
new ModelMapper();
CustomerDTO dto =
mapper.map(
customer,
CustomerDTO.class);
MapStruct Example
@Mapper
public interface CustomerMapper {
CustomerDTO toDTO(
Customer customer);
}
Generated automatically.
MapStruct Flow
flowchart LR
A[Entity]
B[MapStruct]
C[DTO]
A --> B
B --> C
Banking Example
Database Entity:
Account Number
Balance
PIN
Internal Audit
DTO Response:
Account Number
Balance
Banking Architecture
flowchart LR
A[Account Entity]
B[Account DTO]
C[API Response]
A --> B
B --> C
Insurance Example
Entity:
Claim Details
Internal Notes
Fraud Score
DTO:
Claim Number
Status
Approved Amount
Insurance Flow
flowchart LR
A[Claim Entity]
B[Claim DTO]
C[Client]
A --> B
B --> C
Microservices Example
Service A:
Customer Service
Service B:
Order Service
Communication uses DTOs.
Microservices Flow
flowchart LR
A[Customer Service]
B[Customer DTO]
C[Order Service]
A --> B
B --> C
API Versioning Example
Version 1:
CustomerDTOv1
Version 2:
CustomerDTOv2
Entities remain unchanged.
Enterprise Examples
Banking
Account Response DTO
Loan DTO
Transaction DTO
Insurance
Claim DTO
Policy DTO
Retail
Order DTO
Product DTO
Healthcare
Patient DTO
Appointment DTO
DTO vs Entity
| DTO | Entity |
|---|---|
| API Layer | Database Layer |
| Lightweight | Rich Model |
| Transfer Data | Persist Data |
| Secure | Internal |
DTO vs VO
| DTO | Value Object |
|---|---|
| Data Transfer | Domain Concept |
| Mutable | Often Immutable |
| API Communication | Business Modeling |
DTO vs DAO
| DTO | DAO |
|---|---|
| Transfer Data | Access Data |
| API Layer | Persistence Layer |
| No SQL | CRUD Logic |
Enterprise Architecture
flowchart LR
A[Client]
B[Controller]
C[Request DTO]
D[Service]
E[Entity]
F[Repository]
G[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
Benefits
✅ Improved Security
✅ Reduced Payload Size
✅ API Versioning Support
✅ Loose Coupling
✅ Cleaner Architecture
✅ Better Performance
Limitations
❌ Extra Classes
❌ Mapping Logic
❌ Additional Maintenance
When To Use
Use DTO when:
- Building REST APIs
- Exposing Data Externally
- Hiding Sensitive Information
- Microservices Communication
- API Versioning
When Not To Use
Avoid when:
- Small Internal Applications
- No External Data Exposure
Interview Questions
What is DTO?
A Data Transfer Object used to move data between layers.
Why Use DTO?
To avoid exposing internal entities.
DTO vs Entity?
Entity persists data.
DTO transfers data.
DTO Mapping Tools?
MapStruct
ModelMapper
DTO in Microservices?
Used for service-to-service communication.
Main Benefit?
Security and loose coupling.
Real Enterprise Example
Fund Transfer API:
Entity:
Account Number
Balance
PIN
Audit Details
DTO:
Account Number
Balance
Client only receives required data.
Key Takeaways
- DTO stands for Data Transfer Object.
- Used to transfer data safely between layers.
- Prevents exposing entities directly.
- Common in REST APIs and Microservices.
- Supports API versioning and security.
- Frequently used with Spring Boot.
- Essential enterprise architecture pattern for modern applications.