Learn Java, Spring Boot, Quarkus, Kotlin, Go, Python, Angular, Vue.js, React.js, React Native, PHP, .Net and even more with CRUD example.
Java Record as DTO in Spring Boot Application
Get link
Facebook
Twitter
Pinterest
Email
Other Apps
Hello everyone, In this article, we will show how we used Java Record as DTO in the Spring Boot application. The GitHub repository link is provided at the end of this tutorial. You can download the source code.
From Java 14 onwards, the record is a special type of class declaration aimed at reducing the boilerplate code.
Technologies used :
Final Project Directory
Maven[pom.xml]
A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project.
Records cannot be used as entities with JPA/Hibernate. JPA entities must have a no-args constructor, and must not be final, two requirements that the record will not support. More Information
The @RestController annotation was introduced in Spring 4.0 to simplify the engendering of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody. @RequestMapping annotation maps HTTP requests to handler methods of MVC and REST controllers.
In the previous tutorial, we created a Spring boot project and build CRUD RESTful Webservices using Spring Boot 3, Spring Data JPA (Hibernate), and MySQL database.
In this tutorial, we will see how to DTO (Data Transfer Object) pattern to transfer the data between the Client and Server in the Spring boot application.
DTO ( Data Transfer Object) Overview
Data Transfer Object Design Pattern is a frequently used design pattern. It is basically used to pass data with multiple attributes in one shot from client to server, to avoid multiple calls to a remote server.
Another advantage of using DTOs on RESTful APIs written in Java (and on Spring Boot), is that they can help to hide implementation details of domain objects (JPA entities). Exposing entities through endpoints can become a security issue if we do not carefully handle what properties can be changed through what operations.
Prerequisites
This tutorial is a continuation of Spring Boot 3 CRUD RESTful WebServices with MySQL Database tutorial so first, you need to create a Spring Boot project with CRUD REST API’s using this tutorial:
Development Steps
1. Create UserDto Class
package net.javaguides.springboot.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @NoArgsConstructor @AllArgsConstructor public class UserDto
2. Change CRUD REST API’s to Return UserDTO to the Client
package net.javaguides.springboot.controller; import lombok.AllArgsConstructor; import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User; import net.javaguides.springboot.exception.ErrorDetails; import net.javaguides.springboot.exception.ResourceNotFoundException; import net.javaguides.springboot.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import java.time.LocalDateTime; import java.util.List; @RestController @AllArgsConstructor @RequestMapping("api/users") public class UserController < private UserService userService; // build create User REST API @PostMapping public ResponseEntitycreateUser(@RequestBody UserDto user)< UserDto savedUser = userService.createUser(user); return new ResponseEntity<>(savedUser, HttpStatus.CREATED); > // build get user by id REST API // http://localhost:8080/api/users/1 @GetMapping("") public ResponseEntity getUserById(@PathVariable("id") Long userId)< UserDto user = userService.getUserById(userId); return new ResponseEntity<>(user, HttpStatus.OK); > // Build Get All Users REST API // http://localhost:8080/api/users @GetMapping public ResponseEntity getAllUsers() < Listusers = userService.getAllUsers(); return new ResponseEntity<>(users, HttpStatus.OK); > // Build Update User REST API @PutMapping("") // http://localhost:8080/api/users/1 public ResponseEntity updateUser(@PathVariable("id") Long userId, @RequestBody UserDto user)< user.setId(userId); UserDto updatedUser = userService.updateUser(user); return new ResponseEntity<>(updatedUser, HttpStatus.OK); > // Build Delete User REST API @DeleteMapping("") public ResponseEntity deleteUser(@PathVariable("id") Long userId)< userService.deleteUser(userId); return new ResponseEntity<>("User successfully deleted!", HttpStatus.OK); > >
3. Create UserMapper Class
Let’s create a UserMapper class to convert the User entity to UserDto and UserDto to the User entity:
package net.javaguides.springboot.mapper; import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User; public class UserMapper < // Convert User JPA Entity into UserDto public static UserDto mapToUserDto(User user)< UserDto userDto = new UserDto( user.getId(), user.getFirstName(), user.getLastName(), user.getEmail() ); return userDto; >// Convert UserDto into User JPA Entity public static User mapToUser(UserDto userDto) < User user = new User( userDto.getId(), userDto.getFirstName(), userDto.getLastName(), userDto.getEmail() ); return user; >>