Hackforge Academy

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);

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community