Java4Shell (CVE-2026-114938) is fixed in Liberica JDK

See details
Posts

DTO in Spring Boot: What It Is and How to Use It

Updated

Catherine Edelveis

37

A DTO (Data Transfer Object) in Spring Boot is a simple object, usually a Java record, that carries data between the API and the service layer without exposing JPA entities. You use request DTOs for incoming JSON and response DTOs for what the client receives.

Sending an entire customer object with a password, credit card number, and national ID to the client sounds like a developer’s nightmare, but in fact, it is a pretty realistic scenario.

The most popular approach to avoiding such situations is to use Data Transfer Objects (DTOs). But are DTOs a necessity or overkill? Is there an alternative approach?

This article covers the essentials of safely passing data between the server and client.

Expect:

  • DTO fundamentals and benefits,
  • A tutorial on using DTOs with records in Spring Boot,
  • A guide to manual vs automated mapping with MapStruct,
  • Additional approaches to retrieving data from the database.

What is a DTO in Spring Boot?

Data Transfer Objects (DTOs) are POJOs that serve as data carriers between processes, layers, or services. Their only purpose is to define the shape of the data passed to or from the client. In this sense, entities can also serve as DTOs if you use an alternative approach to creating additional data carrier classes.

In this article, I’ll refer to classes with JPA annotations as entities and records without JPA annotations as DTOs.

How can DTOs help us in production?

  • They enable the separation of concerns. While entities represent the domain's relational model, DTOs aim to transfer data between system layers. Consequently, they help to avoid the exposure of DB internal details to API consumers.
  • They enhance security. DTOs help developers expose only necessary information, keeping confidential data such as passwords safe.
  • They can improve performance. DTOs can carry data only from necessary fields, helping to avoid serialization and network overhead.
  • They can be used for validation. Constraints on a request DTO check incoming data at the API boundary.

DTO vs Entity vs DAO vs POJO

DTO

Entity

DAO

POJO

Purpose

Carries data between layers or to and from the client

Represents a persistent domain object mapped to a table

Encapsulates data access: queries and persistence operations

A plain Java object with no framework requirements

Application layer

API boundary and service layer

Persistence (domain model)

Persistence (data access)

Any

Typical annotations

None, or validation/Jackson annotations (@NotBlank, @JsonProperty)

@Entity, @Table, @Id, @Column

@Repository, or none for a Spring Data repository interface

None

Contains logic

No

Possibly simple domain logic, but no data access

Data-access logic only

Depends on the class

Typical mutability

Often immutable

Usually mutable

Usually stateless

Either

The categories aren't mutually exclusive: DTOs and entities are usually POJOs too, and in Spring Boot, a Spring Data repository plays the DAO role.

How to Use DTOs with Spring Boot

This article focuses on using DTOs with Spring Data JPA. The Database Connectivity API — JPA, JDBC, jOOQ, etc. — doesn’t change the concept of DTOs, but it may affect the mapping strategy. Therefore, the article may be replenished with other APIs in the future.

To complete this guide, you will need:

  • Java 25 (LTS). The examples use Spring Boot 4.1.2, which itself runs on Java 17 or later, but the demo project targets Java 25. As it is a Spring Boot demo, I'm using Liberica JDK recommended by Spring.
  • Your favorite IDE. I'm using IntelliJ IDEA.
  • The following dependencies: Spring Web MVC, Spring Data JPA, H2 Database, Validation.

The code from this article is available on GitHub.

DTOs with Modern Java: Using Records

Records are data carriers with final components. On the surface, they require only the specification of the fields. Under the hood, they make all fields private and final and automatically create accessors, a constructor, equals(), hashCode(), and toString(). This makes the declaration of simple data carriers more concise.

DTOs are a good match for records. A conventional class may still be preferable when a framework or library expects a no-argument constructor or JavaBeans setters.

For instance, let’s look at the following entity class:

@Entity
@Table(name="employee")
public class Employee {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    private String password;

// getters, setters, constructors are omitted for brevity

}

Let’s create the corresponding DTO:

public record EmployeeDTO(Long id,
                          String name,
                          String email) {
}

As you can see, EmployeeDTO contains only three fields and no password.

This was an example of a Response DTO. In some cases, if DTO and entity fields match, one DTO may suffice.

But what if the data you receive from the client differs from the data you send from the server? In this case, you can create a Request DTO in addition to a Response DTO.

The Request DTO for Employee may look like this:

public record EmployeeRequestDTO(String name,
                                 String email,
                                 String password) {
}

But you can enhance it with validation because records allow us to add annotations to their fields:

import jakarta.validation.constraints.NotNull;

public record EmployeeRequestDTO(@NotNull String name,
                                 @NotNull String email,
                                 @NotNull String password) {
}

This record illustrates where constraints go. The demo’s employee endpoint only reads data. The customer POST below shows how @Valid activates validation for an incoming request body.

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CustomerResponse createCustomer(@Valid @RequestBody CreateCustomerRequest request) {
      return customerService.create(request);
}

What if the entity contains nested entities? Let’s look at the following example, where Customer has a List of Orders, and Order contains Customer:

@Entity
@Table(name="customers")
public class Customer {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    private String password;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "customer_id")
    List<Order> orders = new ArrayList<>();

    @Enumerated(EnumType.STRING)
    private Status status;

// getters, setters, constructors are omitted for brevity

}


@Entity
@Table(name="orders")
public class Order {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "total_price")
    private double totalPrice;

    @ManyToOne(cascade =
            {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="customer_id")
    private Customer customer;

// getters, setters, constructors are omitted for brevity
}

In this case, we can use a composite DTO. In the demo, CustomerResponse contains a list of OrderResponse records, a customer status, and the sum of order prices:

public record CustomerResponse(Long id,
                               String name,
                               String email,
                               String status,
                               List<OrderResponse> orders,
                               double totalExpenses) {
}

public record OrderResponse(Long id,
                            double totalPrice) {

}

Request and response DTOs with validation

Let's put both kinds of DTOs to work in an endpoint that creates a customer. First, the records:

// CreateCustomerRequest.java
package dev.cat.customer.dto;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

public record CreateCustomerRequest(@NotBlank String name,
                                    @NotBlank @Email String email,
                                    @NotBlank String password) {
}

// CustomerResponse.java
package dev.cat.customer.dto;

import java.util.List;

public record CustomerResponse(Long id,
                               String name,
                               String email,
                               String status,
                               List<OrderResponse> orders,
                               double totalExpenses) {
}

Then, the controller:

package dev.cat.customer.controller;

import dev.cat.customer.dto.CreateCustomerRequest;
import dev.cat.customer.dto.CustomerResponse;
import dev.cat.customer.service.CustomerService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/customers")
public class CustomerController {

    private final CustomerService customerService;

    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public CustomerResponse createCustomer(@Valid @RequestBody CreateCustomerRequest request) {
        return customerService.create(request);
    }
}

Client → Controller (DTO) → Service (maps) → Repository (Entity)

The service maps the request to a Customer, saves it, and maps the saved entity to CustomerResponse. The MapStruct section shows the service method that connects these steps.

The request DTO defines what the API accepts. The response DTO defines what it exposes. Their fields can differ. The client supplies a password but no ID. On success, it receives HTTP 201 with the generated ID, status, orders, and total expenses, along with the customer’s name and email. The response omits the password. The demo stores it as submitted to keep the example focused on mapping. In a real application, hash passwords before storing them.

Add spring-boot-starter-validation to install a Jakarta Bean Validation provider. On the controller parameter, @Valid tells Spring MVC to check the record’s constraints. A blank name or invalid email yields HTTP 400 Bad Request before the controller method runs. The error body depends on the application’s error handling.

Separate DTOs also give an OpenAPI generator distinct schemas for input and output. See documenting REST APIs with Swagger in Spring Boot.

Mapping Entities to DTOs: Manual Mapping

Manual mapping is a reliable approach to working with DTOs, as you can tailor the mappers exactly as needed. In addition, manual mapping doesn’t require third-party libraries. Hence, no surprises at runtime and a smooth debugging experience.

Let’s see how we can implement mappers for our DTOs. A mapper is a regular Java class with primary methods toDto() and toEntity() and possibly additional methods for formatting and computing values.

A basic mapper for our Customer model could look like that:

@Component
public class ManualCustomerMapper {

    public CustomerResponse mapToCustomerResponse(Customer customer) {
        List<OrderResponse> orderResponses = customer.getOrders()
                .stream()
                .filter(Objects::nonNull)
                .map(this::mapToOrderResponse)
                .toList();

        return new CustomerResponse(
                customer.getId(),
                customer.getName(),
                customer.getEmail(),
                statusToString(customer.getStatus()),
                orderResponses,
                orderResponses
                        .stream()
                        .filter(Objects::nonNull)
                        .map(OrderResponse::totalPrice)
                        .reduce(0.0, Double::sum));
    }

    private String statusToString(Status status) {
        return status != null ? status.name() : null;
    }

    public OrderResponse mapToOrderResponse(Order order) {
        return new OrderResponse(order.getId(), order.getTotalPrice());
    }

    public Customer mapToCustomer(CreateCustomerRequest customerRequest) {
        Customer customer = new Customer();
        customer.setName(customerRequest.name());
        customer.setEmail(customerRequest.email());
        customer.setPassword(customerRequest.password());
        customer.setStatus(Status.BRONZE);
        return customer;
    }
}

Then, we can add this mapper to CustomerService:

@Service
public class CustomerService {

    private final CustomerRepository customerRepository;
    private final ManualCustomerMapper customerMapper;

    public CustomerService(CustomerRepository customerRepository, ManualCustomerMapper customerMapper) {
        this.customerRepository = customerRepository;
        this.customerMapper = customerMapper;
    }

    public List<CustomerResponse> findAll() {

        return customerRepository
                .findAll()
                .stream()
                .map(customerMapper::mapToCustomerResponse)
                .toList();
    }
}

If the API requires a different format for some data, you can add a value transformation to the mapper. Here, statusToString() converts the entity’s Status enum to a string while preserving a missing status. The mapper also sums the order prices into totalExpenses. Both mappers assign new customers the demo’s default BRONZE status.

The demo stores the enum by name using @Enumerated(EnumType.STRING):

public enum Status { BRONZE, SILVER, GOLDEN }

When we want to make a request, we usually prefer to reference the object by ID, which is a typical pattern of usage for DTOs. We don’t want to fetch an object from the database when creating a model object to avoid extra SELECTs. So, we can use EntityManager and its method getReference() to obtain a reference by ID whose state can be loaded later:

public class ManualOrderMapper {

    private final EntityManager entityManager;

    public ManualOrderMapper(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public Order toOrder(Long customerId, OrderRequest request) {
        Order order = new Order();
        order.setCustomer(entityManager.getReference(Customer.class, customerId));
        order.setTotalPrice(request.totalPrice());
        return order;
    }
}

DTO Projections

To avoid overfetching and related N+1 / LazyInitializationException issues when building a DTO, you can use query-time projection to fetch only the required fields. In this case, you get the DTO based on the attribute types returned by a SQL query without the need for a mapper.

Let’s look at the following Entity and its DTO:

@Entity
@Table(name="device")
public class Device {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String model;
    @ManyToOne(fetch = FetchType.LAZY, cascade =
            {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="manufacturer_id")
    private Manufacturer manufacturer;
    private String serialNumber;
    private int lotNumber;

    @ManyToOne(fetch = FetchType.LAZY, cascade =
            {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="supplier_id")
    private Supplier supplier;
// getters, setters, constructors, etc. are omitted for brevity
}

public record DeviceDTO(String serialNumber, String model) {
}

We want to return only the serial number and model, leaving behind all other fields, including nested objects.

If the DTO field names match exactly the entity field names, you can use a query method:

public interface DeviceRepository extends CrudRepository<Device, Long> {
    List<DeviceDTO> findByLotNumber(int lotNumber);
}

You can also return a Projection DTO using JPQL or Native queries. Here’s the example with a JPQL query. Note that it refers to the entity and its attributes, not to the table and its columns:

public interface DeviceRepository extends CrudRepository<Device, Long> {

    @Query("SELECT d.serialNumber, d.model FROM Device d WHERE d.lotNumber = :lotNumber")
    List<DeviceDTO> findByLotNumber(int lotNumber);

}

Spring Data JPA can rewrite this multi-select as a DTO constructor expression. You can also write that expression explicitly, as shown below.

You can also use dynamic projections in case you want to decide whether to return an Entity or a DTO at invocation time:

public interface DeviceRepository extends CrudRepository<Device, Long> {
    <T> Collection<T> findByLotNumber(int lotNumber, Class<T> type);
}

Then, in the service layer:

void doSomethingMeaningful(int lotNumber) {

  Collection<Device> devices =
    deviceRepository.findByLotNumber(123456, Device.class);

  Collection<DeviceDTO> deviceDtos =
    deviceRepository.findByLotNumber(123456, DeviceDTO.class);
}

What if we have nested entities and want to include specific fields into our DeviceDTO, such as the name of the manufacturer or a ManufacturerDTO?

In case you want to retrieve only some fields from nested entities, you can build a JPQL query:

public record DeviceDTOwithManufacturerName(String serialNumber,
                                            String model,
                                            String manufacturerName) {}

public interface DeviceRepository extends CrudRepository<Device, Long> {

  @Query("""
     select new dev.cat.device.dto.DeviceDTOwithManufacturerName(
       d.serialNumber, d.model, d.manufacturer.name)
     from Device d
     where d.lotNumber = :lotNumber
  """)
  List<DeviceDTOwithManufacturerName> findByLotNumberWithManufacturerName(int lotNumber);
}

Note that with the JPQL query, we must invoke the DTO constructor using a new keyword and a fully qualified name of the DTO.

What if you have nested DTOs? The demo uses Hibernate’s HQL extension for nested constructor expressions. For portable JPQL, project the fields into a flat DTO and assemble the nested DTO in Java.

public record DeviceDTOwithManufacturerDTO(String serialNumber,
                                           String model,
                                           ManufacturerDTO manufacturer) {
}
public record ManufacturerDTO(Long id, String name) {
}

Most JPA providers, including Hibernate, support nested constructor expressions so that you can write a query for that as well:

public interface DeviceRepository extends CrudRepository<Device, Long> {

  @Query("""
     select new dev.cat.device.dto.DeviceDTOwithManufacturerDTO(
       d.serialNumber, d.model,
       new dev.cat.device.dto.ManufacturerDTO(m.id, m.name)
     )
     from Device d
     join d.manufacturer m
     where d.lotNumber = :lotNumber
  """)
  List<DeviceDTOwithManufacturerDTO> findByLotNumberNested(int lotNumber);
}

For all projection types and their limitations, see the Spring Data JPA projections documentation.

Automated Mapping with MapStruct

If you are fine with doing mapping in the application instead of the database, you can consider using the MapStruct library that automates DTO mapping. MapStruct aims to reduce the boilerplate and error-prone mapping code that developers have to write and generates mappers automatically at compile-time.

To use MapStruct, you need to add a MapStruct dependency:

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.6.3</version>
</dependency>

And a MapStruct processor to the build plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.15.0</version>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>1.6.3</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

In a perfect world, if our Employee didn’t have a password so that entity and DTO fields could be the same:

@Entity
@Table(name="employee")
public class Employee {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
// getters, setters, constructors are omitted for brevity

}

public record EmployeeDTO(Long id, String name, String email) {
}

You can can create a Mapper interface with the @Mapper annotation and two simple methods:

@Mapper
public interface EmployeeMapper {
   EmployeeMapper INSTANCE = Mappers.getMapper(EmployeeMapper.class);
   EmployeeDTO mapEmployeeToDto(Employee employee);
   Employee mapDtoToEmployee(EmployeeDTO dto);
}

The INSTANCE field can be used when you need to perform the mapping in your Service classes (or wherever you prefer to do the mapping).

That’s it! MapStruct generates the mapper implementation at compile time. Below is the implementation MapStruct generated for us under target/generated-sources/annotations/dev/cat/EmployeeMapperImpl.java:

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2026-11-10T14:39:34+0300",
    comments = "version: 1.6.3, compiler: javac, environment: Java 25.0.2 (BellSoft)"
)
public class EmployeeMapperImpl implements EmployeeMapper {

    @Override
    public EmployeeDTO mapEmployeeToDto(Employee employee) {
        if ( employee == null ) {
            return null;
        }

        Long id = null;
        String name = null;
        String email = null;

        id = employee.getId();
        name = employee.getName();
        email = employee.getEmail();

        EmployeeDTO employeeDTO = new EmployeeDTO( id, name, email );

        return employeeDTO;
    }

    @Override
    public Employee mapDtoToEmployee(EmployeeDTO dto) {
        if ( dto == null ) {
            return null;
        }

        Employee employee = new Employee();

        employee.setId( dto.id() );
        employee.setName( dto.name() );
        employee.setEmail( dto.email() );

        return employee;
    }
}

But our Employee has a password, right? We don’t want to map the password to EmployeeDTO. In this case, we can exclude the missing field from mapping by adding the unmappedTargetPolicy to the @Mapper annotation:

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface EmployeeMapper {
   EmployeeMapper INSTANCE = Mappers.getMapper(EmployeeMapper.class);
   EmployeeDTO mapEmployeeToDto(Employee employee);
   Employee mapDtoToEmployee(EmployeeDTO dto);
}

As a result, MapStruct will ignore unmapped properties and map only what can be mapped. In addition, it won’t issue any warnings during compilation.

How about nested DTOs and calculated values? Can MapStruct handle these use cases?

We’ll reuse the same CustomerResponse and OrderResponse records from the manual mapping example.

The OrderMapper is nothing fancy, it’s just the interface like we saw above:

@Mapper(unmappedTargetPolicy = org.mapstruct.ReportingPolicy.IGNORE)
public interface OrderMapper {

    OrderMapper INSTANCE = Mappers.getMapper(OrderMapper.class);
    OrderResponse mapToOrderResponse(Order order);

}

The CustomerMapper is more complex as it needs to perform certain calculations and also, call the OrderMapper instance to map Orders to DTOs. We should make it an abstract class in this case and define our custom logic:

@Mapper(unmappedTargetPolicy = org.mapstruct.ReportingPolicy.IGNORE,
        componentModel = "spring")
public abstract class CustomerMapper {

    @Mapping(target = "status", constant = "BRONZE")
    public abstract Customer mapToCustomer(CreateCustomerRequest request);

    public CustomerResponse mapToCustomerResponse(Customer customer) {

        List<OrderResponse> orderResponses = customer.getOrders()
                .stream()
                .filter(Objects::nonNull)
                .map(OrderMapper.INSTANCE::mapToOrderResponse)
                .toList();

        double totalExpenses = orderResponses.stream()
                .filter(Objects::nonNull)
                .map(OrderResponse::totalPrice)
                .reduce(0.0, Double::sum);

        return new CustomerResponse(
                customer.getId(),
                customer.getName(),
                customer.getEmail(),
                statusToString(customer.getStatus()),
                orderResponses,
                totalExpenses);
    }

    private String statusToString(Status status) {
        return status != null ? status.name() : null;
    }
}

MapStruct generates the implementation of the abstract mapToCustomer() method, while mapToCustomerResponse() keeps our custom logic.

Note that this class is annotated additionally with componentModel = "spring". This is because we will use this mapper as a regular Spring bean and inject it into CustomerService:

@Service
public class CustomerService {

    private final CustomerRepository customerRepository;
    private final CustomerMapper customerMapper;

    public CustomerService(CustomerRepository customerRepository, CustomerMapper customerMapper) {
        this.customerRepository = customerRepository;
        this.customerMapper = customerMapper;
    }

    public List<CustomerResponse> findAll() {

        return customerRepository
                .findAll()
                .stream()
                .map(customerMapper::mapToCustomerResponse)
                .toList();
    }

    public CustomerResponse create(CreateCustomerRequest request) {
        Customer customer = customerMapper.mapToCustomer(request);
        return customerMapper
                .mapToCustomerResponse(customerRepository.save(customer));
    }
}

That’s it! You mastered the essentials of the Mapstruct library. You can read about other use cases and possible configurations in the documentation.

Do We Always Need DTOs? Alternatives to Consider

DTOs are a solid approach to separating the data persistence layer from the API. However, when you have a small and simple application, or you are writing a demo to showcase some Spring features and whatsnot, DTOs may become an unnecessary layer of complexity. In some cases, it is easier to start simple and add DTOs as the business logic becomes more complex.

Importantly, having the DTO layer is a de-facto standard of writing enterprise applications, but it is not carved in stone. You must understand when you need to use DTOs and when they are unnecessary.

In the latter case, you can rely on Jackson to limit the data visibility to the allowed degree. Here, we’ll look at two solutions Jackson provides to use any class as a DTO: @JsonIgnore and @JsonView annotations.

Using @JsonIgnore and @JsonView

The @JsonIgnore annotation instructs that a field must be ignored when serializing and deserializing the Entity. For instance, we could annotate the password field of the Student entity like that:

@Entity
@Table(name="student")
public class Student {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    @JsonIgnore
    private String password;

// getters, setters, constructors are omitted for brevity

}

This way, the resulting JSON won’t contain the password when Jackson serializes the Entity, and instead of several DTOs, we have only our Entity. It is not a security guarantee, though: the password is still part of the object and can leak through logs or another serialization path. For a broader picture, see our guide to Java application security.

Let’s consider another situation. What if we don’t want to return the student’s email to the regular users of the API, but want to return it to the admin, for instance?

If we used DTOs, we would have to create two more records: one without email and password, and another with email but without password.

But actually, we could use the @JsonView annotation. This annotation enables us to define multiple views for the same object. The fields are annotated with one or several view classes, and you select which views to use for serialization.

For instance, let’s look at the following Views class with two embedded static classes, Public and Internal:

public class Views {
    public static class Public {}
    public static class Internal extends Public {}
}

In the Student class, all the fields annotated with @JsonView(Views.Public.class) should be available to the general audience and internal personnel. On the other hand, fields annotated with @JsonView(Views.Internal.class) should be visible only to internal personnel:

@Entity
@Table(name="student")
public class Student {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonView(Views.Public.class)
    private Long id;

    @JsonView(Views.Public.class)
    private String name;

    @JsonView(Views.Internal.class)
    private String email;

    @JsonIgnore
    private String password;

// getters, setters, constructors are omitted for brevity

}

Now, how do we handle these annotations in the Controller?

Fields annotated with @JsonIgnore will be silently ignored; no need to update the Controllers. To select the view for serialization, add @JsonView to the relevant controller methods:

@GetMapping("/student")
@JsonView(Views.Public.class)
public Student getStudent(Long id) {
    return studentService.findById(id);
}

@GetMapping("/admin/student")
@JsonView(Views.Internal.class)
public Student getStudentInternal(Long id) {
    return studentService.findById(id);
}

The /admin/student mapping selects the internal view. The demo has no authorization check for this route. To restrict the email to admins, enforce authorization separately.

A quick compatibility note: Spring Boot 4 uses Jackson 3 by default. Jackson 3 moves its core APIs, such as ObjectMapper, from com.fasterxml.jackson to tools.jackson, but jackson-annotations keeps the com.fasterxml.jackson.annotation package, so the @JsonIgnore and @JsonView imports above stay the same. Spring Boot 3.5 uses Jackson 2, so code that works with the mapper or custom serializers needs different imports depending on the Spring Boot version. Learn more in our guide on migrating from Spring Boot 3 to Spring Boot 4 and the official Spring Boot 4.0 Migration Guide.

JPA Entity Graph

With Spring Data JPA, there’s always a risk of N+1 and related issues. Developers can choose a fetching strategy for nested entities, FetchType.LAZY or FetchType.EAGER, to tackle such issues. The problem with these fetching strategies is that they are static and cannot be switched at runtime.

However, there is a way to implement a per-case-fetch plan thanks to JPA Entity Graph.

With JPA Entity Graph, developers let the persistence layer know which associations should be fetched eagerly for a given query. As a result, the JPA provider can fetch these associations together with the root entity, often in one SELECT query with joins, as in the examples below, instead of using additional SELECT queries, which can result in better performance. The actual SQL depends on the mappings, the query, and the provider.

You can define the entity graph with annotations or programmatically with the JPA API. We’ll look at annotations in this article.

To define one entity graph, we use the @NamedEntityGraph annotation applied at the class level. Note that multiple @NamedEntityGraph annotations can be applied to define several graphs (the annotation is repeatable since JPA 2.2, so you don't need the @NamedEntityGraphs container).

@NamedEntityGraph is applied to the root entity. Take our Device class, for instance. As it is the root entity used in the queries, we define the named entity graph in the Device class.

This annotation allows us to specify the attributes that we want to load for this entity. The attributes are specified with @NamedAttributeNode:

@NamedEntityGraph(
        name = "device-entity-graph",
        attributeNodes = {
                @NamedAttributeNode("manufacturer"),
                @NamedAttributeNode("supplier"),
        }
)
@Entity
@Table(name="device")
public class Device { 
   @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String model;
    @ManyToOne(fetch = FetchType.LAZY, cascade =
            {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = "manufacturer_id")
    private Manufacturer manufacturer;
    private String serialNumber;
    private int lotNumber;

    @ManyToOne(fetch = FetchType.EAGER, cascade =
            {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = "supplier_id")
    private Supplier supplier;
}

Suppose the Manufacturer has a nested Address and we want to load both. Replace the previous graph with this version, which uses @NamedSubgraph. This is the definition used in the demo and in the queries below:

@NamedEntityGraph(
        name = "device-entity-graph",
        attributeNodes = {
                @NamedAttributeNode(value = "manufacturer", subgraph = "address-subgraph")
        },
        subgraphs = {
                @NamedSubgraph(
                        name = "address-subgraph",
                        attributeNodes = {
                                @NamedAttributeNode("address")
                        }
                )
        }
)
@Entity
@Table(name = "device")
public class Device { 
//...
}

Let’s now see how we can load a graph dynamically.

There are two properties, aka hints, that let us specify whether we want to load or fetch the Entity Graph:

  • jakarta.persistence.fetchgraph: the provider must fetch attributes in the graph and treats unspecified attributes as lazy. It may still fetch additional state. In the Hibernate SQL shown below, the fetch graph omits the supplier join.
  • jakarta.persistence.loadgraph: attributes specified in the graph will also be loaded eagerly, but all other attributes will be loaded according to their fetching strategy. So, the supplier will be loaded eagerly as well.
public class CustomDeviceRepositoryImpl implements CustomDeviceRepository {

    private final EntityManager entityManager;

    public CustomDeviceRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public Device findByIdWithFetchGraph(Long id) {
        var entityGraph = entityManager.getEntityGraph("device-entity-graph");
        Map<String, Object> properties = new HashMap<>();
        properties.put("jakarta.persistence.fetchgraph", entityGraph);
        return entityManager.find(Device.class, id, properties);
    }

    @Override
    public Device findByIdWithLoadGraph(Long id) {
        var entityGraph = entityManager.getEntityGraph("device-entity-graph");
        Map<String, Object> properties = new HashMap<>();
        properties.put("jakarta.persistence.loadgraph", entityGraph);
        return entityManager.find(Device.class, id, properties);
    }

    @Override
    public Device findByIdWithoutGraph(Long id) {
        return entityManager.find(Device.class, id);
    }
}

Note that if you use the find() method of EntityManager without specifying the graph, all fields will be loaded as per their fetching strategy. So, the manufacturer will be loaded lazily, and the supplier eagerly.

Here’s the resulting SQL of fetching devices without the entity graph. As you can see, the manufacturer was lazy loaded, and supplier eagerly loaded as per the defined fetching strategy:

SELECT 
    d1_0.id,
    d1_0.lot_number,
    d1_0.manufacturer_id,
    d1_0.model,
    d1_0.serial_number,
    s1_0.id,
    s1_0.name
FROM device d1_0
LEFT JOIN supplier s1_0 
       ON s1_0.id = d1_0.supplier_id
WHERE d1_0.id = ?;

Here’s the resulting SQL of fetching devices with the fetch graph. The supplier was loaded lazily. The manufacturer was loaded eagerly plus the address:

SELECT 
    d1_0.id,
    d1_0.lot_number,
    m1_0.id,
    a1_0.id,
    a1_0.city,
    a1_0.country,
    a1_0.zip,
    m1_0.license,
    m1_0.name,
    d1_0.model,
    d1_0.serial_number,
    d1_0.supplier_id
FROM device d1_0
LEFT JOIN manufacturer m1_0 
       ON m1_0.id = d1_0.manufacturer_id
LEFT JOIN address a1_0 
       ON a1_0.id = m1_0.address_id
WHERE d1_0.id = ?;

Here’s the resulting SQL of fetching devices with the load graph. Both the supplier and the manufacturer were loaded eagerly:

SELECT 
    d1_0.id,
    d1_0.lot_number,
    m1_0.id,
    a1_0.id,
    a1_0.city,
    a1_0.country,
    a1_0.zip,
    m1_0.license,
    m1_0.name,
    d1_0.model,
    d1_0.serial_number,
    s1_0.id,
    s1_0.name
FROM device d1_0
LEFT JOIN manufacturer m1_0 
       ON m1_0.id = d1_0.manufacturer_id
LEFT JOIN address a1_0 
       ON a1_0.id = m1_0.address_id
LEFT JOIN supplier s1_0 
       ON s1_0.id = d1_0.supplier_id
WHERE d1_0.id = ?;

You can use this approach to return stripped down entities or combine it with DTOs.

DTO best practices

A short checklist to keep your DTOs useful:

  • Make DTOs immutable. Records are a great default.
  • Use distinct request and response types. What the API accepts and what it exposes evolve differently.
  • Don't expose JPA entities from controllers. If you deliberately go with the Jackson-based alternatives described above, be aware of their limits.
  • Validate at the API boundary. Put constraints on request DTOs and annotate controller parameters with @Valid.
  • Keep mapping in one place. Use a dedicated mapper, manual or MapStruct, called from the service layer.
  • Keep business logic out of DTOs. Formatting and computed values belong in mappers, business rules in services.
  • Fetch only what you need. For read-heavy endpoints, query-time projections can skip the entity altogether.
  • Evolve DTOs together with the API. They are your public contract: add fields in a backward-compatible way and version the API for breaking changes.

FAQ

What does DTO stand for?

DTO stands for Data Transfer Object. It is an object whose only job is to carry data between processes, layers, or services, for example, between a Spring Boot API and its clients.

Is a DTO the same as a POJO?

Not exactly. POJO (Plain Old Java Object) describes how a class is written: without framework-specific base classes or interfaces. DTO describes what the class is for, which is carrying data, so most DTOs are POJOs, but not every POJO is a DTO.

What is the difference between a DTO and a DAO?

A DTO holds data, while a DAO (Data Access Object) retrieves and stores it by encapsulating queries and persistence operations. In Spring Boot, Spring Data repositories play the DAO role, and they can even return DTOs directly via projections.

Why use a DTO instead of returning a JPA entity?

Returning an entity ties your API contract to the database schema and can expose sensitive fields, such as passwords. It can also cause lazy loading and serialization issues with entity relationships. A DTO lets you decide exactly what the client sees and change the schema without breaking API consumers.

Is a Java record a good choice for a DTO?

Yes. Records give you a concise, fixed set of components plus a constructor and accessors. Their immutability is shallow, so copy mutable components such as lists when you need an immutable snapshot.

Recap

A quick summary?

DTOs are a practical way to separate the persistence model from the API contract and keep sensitive data hidden. Java records make DTOs concise and give them final components, and mapping strategies include manual mappers and code generators such as MapStruct.

On the other hand, using DTOs may lead to having dozens of additional classes you must maintain.

You can use Jackson capabilities to trim or shape JSON output directly from entities, such as annotations like @JsonIgnore or @JsonView. In this case, there’s no need to write lots of additional classes for DTOs and Mappers.

The downside of using annotations could be hundreds of annotations in your code. In addition, there’s a risk of additional complexity if you want to use entity fields with various views. These annotations should be used with caution and understanding of what you are doing.

You can use the JPA Entity Graph in addition to or instead of DTOs to control the fetching strategy at runtime.

Learned something new from this article? Great! Don’t forget to subscribe to our newsletter for a monthly digest of our articles and videos on Java development and news in the Java world!

 

Subcribe to our newsletter

figure

Read the industry news, receive solutions to your problems, and find the ways to save money.

Further reading