Category: java
DTO in spring boot
Published on 16 Jul 2026
Explanation
DTO (Data Transfer Object) is used to transfer data between the client and server. Instead of exposing entity classes directly, APIs send and receive DTOs.
Code:
public class StudentDTO {
private String name;
private String email;
// Getters and Setters
}
Explanation
Entity classes represent database tables, while DTO classes represent API request and response models. This separates persistence logic from API design.
Code:
@Entity
public class Student {
@Id
private Long id;
private String name;
private String email;
private String password;
}
Explanation
Convert an Entity to a DTO before returning data to clients. This prevents exposing sensitive fields such as passwords.
Code:
StudentDTO dto = new StudentDTO(); dto.setName(student.getName()); dto.setEmail(student.getEmail());
Explanation
Controllers should receive DTO objects instead of Entity objects. The service layer converts DTOs into Entities before saving them.
Code:
@PostMapping
public StudentDTO createStudent(@RequestBody StudentDTO dto) {
return dto;
}
Explanation
DTOs improve security, maintainability, and API flexibility. Libraries like ModelMapper can automatically convert between Entities and DTOs.
Code:
@Autowired private ModelMapper modelMapper; StudentDTO dto = modelMapper.map(student, StudentDTO.class);