SoFunction
Updated on 2025-03-08

Example of method using DTO layer in SpringBoot development

During Spring Boot development, using the DTO (Data Transfer Object) layer is a very common practice. The DTO layer is an intermediate layer introduced between the business logic layer and the data access layer of an application, and is used to transfer data between different layers. This article will introduce the basic syntax of the DTO layer and why the DTO layer is needed in Spring Boot development, and provide actual case code.

Why do you need a DTO layer?

In Spring Boot development, there are several important reasons for using the DTO layer:

1. Data encapsulation

The DTO layer can encapsulate data from multiple entity classes into a DTO object, making data transmission more convenient. DTO objects usually only contain data fields that need to be transferred, and do not contain business logic. This can reduce the size of data transmission and improve performance.

2. Decoupling

The DTO layer can decouple the business logic layer and the data access layer. The business logic layer can interact with the data access layer through DTO objects without directly operating the database entity class. This can reduce the coupling of the code and improve the maintainability and testability of the code.

3. Data format conversion

The DTO layer can convert data formats. For example, convert the data of the database entity class into the JSON format data required by the front-end, or convert the JSON data passed by the front-end into the format required by the database entity class. This can simplify the code logic of data conversion and improve development efficiency.

4. Security

The DTO layer can be used to filter sensitive data. During data transmission, sensitive data that does not need to be transmitted can be filtered out through the DTO layer to protect the security of the data.

Sample code

Better encapsulation of data

First, define a DTO class to encapsulate the data fields that need to be transmitted:

public class UserDto {
    private String username;
    private String email;

    // Omit the constructor and getter/setter methods}

Then, use DTO objects in the business logic layer for data transmission:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public UserDto getUserById(Long id) {
        User user = (id);
        
        // Convert User object to UserDto object        UserDto userDto = new UserDto();
        (());
        (());
        
        return userDto;
    }

    //Omit other business methods}

In the above code,getUserByIdMethod gets aUserobject, then convert it toUserDtoObject, contains only data fields that need to be transferred.

Finally, use DTO objects in the controller layer for data transfer:

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public UserDto getUserById(@PathVariable Long id) {
        // Call the business logic layer method to obtain the UserDto object        UserDto userDto = (id);
        
        return userDto;
    }

    //Omit other controller methods}

In the above code,getUserByIdMethod calls the business logic layer method to obtain aUserDtoobject, and then return it as a response to the frontend.

By using the DTO layer, data encapsulation, decoupling, data format conversion and data security can be achieved. This makes the code clearer, maintainable and testable.

Prevent triggering of parameterless constructors

When delivered directlyUserWhen class, the parameterless constructor will be triggered. This is because in Spring Boot, the default parameterless constructor is used to create an object, and then the object's properties are set through reflection.

Below is a sample code that demonstrates when passed directlyUserWhen class, the case where the parameterless constructor is triggered:

public class User {
    private String username;
    private String email;

    public User() {
        ("User constructor called");
    }

    //Omit other constructors and getter/setter methods}

@RestController
@RequestMapping("/users")
public class UserController {
    @PostMapping("/")
    public void createUser(@RequestBody User user) {
        // The parameterless constructor will be triggered when creating a User object        ("User created: " + ());
    }
}

In the above code,UserThe class defines a parameterless constructor and outputs a log in the constructor.UserControllerIn the classcreateUserMethod Use@RequestBodyAnnotation converts JSON data in the request body intoUserObject. When the request arrives, Spring Boot will automatically create aUserobject and trigger parameterless constructor.

When we send a POST request to/users/Interface and pass the following JSON data:

{
  "username": "john",
  "email": "john@"
}

The console will output the following logs:

User constructor called
User created: john

You can see that when directly passedUserWhen the class is used, the parameterless constructor will be triggered and aUserObject.

It should be noted that ifUserOther constructors are defined in the class, and Spring Boot will select the appropriate constructor according to certain rules to create objects. For example, if a constructor with parameters is defined and no parameter-free constructor is defined, the constructor with parameters is triggered when the object is created.

To sum up, when directly passedUserWhen class, the parameterless constructor will be triggered. This is because Spring Boot uses the parameterless constructor by default to create objects. If you need to use other constructors, you can define and configure them according to your specific needs.

This is all about this article about using the DTO layer in SpringBoot development. For more related content on SpringBoot's use of the DTO layer, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!