0
0
Spring Bootframework~5 mins

Why DTOs matter in Spring Boot

Choose your learning style9 modes available
Introduction

DTOs help move only the needed data between parts of an app. They keep things simple and safe.

When sending data from a server to a client in a web app.
When you want to hide sensitive info from users.
When you need to combine data from different sources into one object.
When you want to avoid sending large or unnecessary data over the network.
When you want to keep your internal data models separate from what external users see.
Syntax
Spring Boot
public class UserDTO {
    private String name;
    private String email;

    // Constructor
    public UserDTO(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

A DTO is a simple class with only fields and getters/setters.

It does not contain business logic or database code.

Examples
Using Java 17 records makes DTOs shorter and immutable.
Spring Boot
public record UserDTO(String name, String email) {}
A DTO can have any fields you want to send or receive.
Spring Boot
public class ProductDTO {
    private String id;
    private String title;
    private double price;

    // getters and setters
}
Sample Program

This Spring Boot controller returns a UserDTO with only name and email. It hides the password field from the client.

Spring Boot
package com.example.demo.dto;

public record UserDTO(String name, String email) {}

package com.example.demo.controller;

import com.example.demo.dto.UserDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user")
    public UserDTO getUser() {
        // Imagine this data comes from a database entity
        String fullName = "Alice Johnson";
        String email = "alice@example.com";
        String password = "secret"; // We don't want to send this

        // We create a DTO with only the safe data
        return new UserDTO(fullName, email);
    }
}
OutputSuccess
Important Notes

DTOs improve security by not exposing sensitive fields.

They make your API responses smaller and faster.

Using records for DTOs reduces boilerplate code.

Summary

DTOs carry only the data you want to share.

They protect your app by hiding internal details.

DTOs keep your code clean and easy to maintain.