Hackforge Academy

Category: React • Beginner

Published on 06 Apr 2026

Explanation

DTO (Data Transfer Object) is used to transfer only required data between client and server instead of sending the entire entity object. This improves security, performance, and clean architecture separation.

Code Example

// Example Entity
@Entity
public class Student {

    @Id
    private Long id;

    private String name;
    private String email;
    private String password;
}

Explanation

Instead of exposing the full entity (including sensitive fields like password), we create a DTO class containing only required fields to send to the client.

Code Example

// StudentDTO class
public class StudentDTO {

    private String name;
    private String email;

}

Explanation

DTO improves security by hiding sensitive fields such as passwords, internal IDs, or database-related information from API responses.

Code Example

// Entity contains password but DTO does not
StudentDTO dto = new StudentDTO();
dto.setName(student.getName());
dto.setEmail(student.getEmail());

Explanation

DTO helps improve performance by transferring only required data instead of sending large entity objects over the network.

Code Example

// Returning DTO instead of Entity
@GetMapping("/student")
public StudentDTO getStudent() {

Student student = studentService.
getStudent();

    StudentDTO dto = new StudentDTO();
    dto.setName(student.getName());
    dto.setEmail(student.getEmail());

    return dto;
}

Explanation

DTO enables separation between database layer and API response structure, allowing flexibility if database schema changes later.

Code Example

// Service layer mapping example
public StudentDTO convertToDTO(
Student student) {

    StudentDTO dto = new StudentDTO();

    dto.setName(student.getName());
    dto.setEmail(student.getEmail());

    return dto;
}

Explanation

In real-world Spring Boot applications like student management or certificate platforms (similar to your training workflows 🎓), DTO is commonly used to send only required student details to frontend applications.

Code Example

// Controller returning DTO list
@GetMapping("/students")
public List<StudentDTO> getAllStudents() {

  return studentService.getAllStudentDTOs();
}

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.