Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Working with DTO | RESTful API
Spring Boot Backend
course content

Зміст курсу

Spring Boot Backend

Spring Boot Backend

1. Backend Development Basics
2. Spring Boot Basics
3. RESTful API
4. Working with Databases
5. Testing Backend Applications

bookWorking with DTO

Using DTOs simplifies and optimizes data exchange by excluding unnecessary fields and providing only the data that a specific client actually needs.

DTOs in this example serve to limit data exchange between the client and server. The ResponseBookDTO is used to send only necessary data (name, author, price) to the client, while the RequestBookDTO allows clients to send required data (date, name, author, price) to the server.

The primary advantage of using DTOs is that they help separate data from business logic and allow for control over which data is transferred between the layers of the application or included in HTTP response messages.

Where Does the DTO Apply?

DTOs are used when there is a need to present data in a specific format, such as for transferring data to a client or receiving information from a client within the context of a REST API.

This is also relevant when interacting between layers in a multi-layered architecture, where data is passed between services and repositories.

Real-life Example

Imagine you are developing an application for an online store. You have an entity called Product, which includes a lot of information: name, description, price, production date, discounts, and so on.

A client requesting a list of products doesn't need all of this information. Instead, you can create a DTO object that contains only the necessary fields (such as the name and price) to send this data to the client.

Example of Use

In our application, the primary model is Book, which is sent by the client and returned by the server.

java

Main

copy
12345678
@Getter @Setter public class Book { private String id; private String name; private String author; private String price; }

However, doesn't it seem that the id field is unnecessary when receiving data from the client, since it is generated at the repository level. We’ll need the id only when returning a response.

This is where DTOs come to the rescue. They allow us to separate the logic and create different versions of the Book model for requests and responses, excluding unnecessary fields like id where appropriate.

In a DTO, an object with the request prefix is used to send data from the client to the server, while an object with the response prefix is used to send data from the server to the client. This separation ensures that only necessary data is exchanged, enhancing both security and efficiency.

java

BookRequestDTO

java

BookResponseDTO

copy
12345
public class BookRequestDTO { private String name; private String author; private String price; }

Now we have two DTOs: one for receiving requests BookRequestDTO and another for sending responses BookResponseDTO.

You may notice that BookResponseDTO and our Book model are identical, which raises the question: why create a separate DTO if we can just use the Book model?

The reason is that if we later decide to add extra information that is only needed at the service level, our Book model would end up passing unnecessary data to the repository level, requiring us to filter it somehow.

Mapper

To conveniently transform objects from one type to another, we use a specialized library.

We can create a separate class where we define static methods and implement the logic for converting objects between types.

MapperBook

MapperBook

copy
1234567891011
public class MapperBook { private static final ModelMapper mapper = new ModelMapper(); public static Book dtoRequestToModel(BookRequestDTO dto) { return mapper.map(dto, Book.class); } public static BookResponseDTO modelToResponseDto(Book book) { return mapper.map(book, BookResponseDTO.class); } }

In this code, the MapperBook class uses the ModelMapper library for automatic object transformation.

It contains two methods: the first is dtoRequestToModel(), which transforms a BookRequestDTO object into a Book model using the map method, and the second is modelToResponseDto(), which converts a Book model into a BookResponseDTO object.

Thanks to ModelMapper, the process of object transformation becomes simpler and more convenient, eliminating the need to manually copy fields.

Adding a DTO to Our Application

Summary

DTO (Data Transfer Object) is a simple object designed for transferring data between layers or components of an application.

In the context of a three-tier architecture, DTO plays a crucial role by ensuring separation of layers and providing an efficient way to exchange data between them.

Thus, using a DTO becomes an optimal solution when it is necessary to manage information between different parts of an application, avoiding the transfer of unnecessary or irrelevant data.

1. What is a `DTO` in the context of programming?
2. Which of the following is the best use of a `DTO`?
What is a `DTO` in the context of programming?

What is a DTO in the context of programming?

Виберіть правильну відповідь

Which of the following is the best use of a `DTO`?

Which of the following is the best use of a DTO?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4
some-alt