DTO Pattern Spring Boot
DTO (Data Transfer Object) is a design pattern that is used to transfer data between layers of an application. In this article, we will look at how to implement the DTO pattern in Spring Boot.
First, let's define the User
entity class that contains the data we want to transfer. The User
entity class has the following fields: firstName
, secondName
, age
, password
, createdAt
, and username
. Here's an example of the User
entity class:
typescriptCopy codeimport java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String secondName;
private int age;
private String password;
private Date createdAt;
private String username;
// Getters and setters
}
Next, we need to create a repository class that can retrieve all users and a single user by ID. We can do this using the JpaRepository
interface provided by Spring Data. Here's an example of the UserRepository
interface:
javaCopy codeimport org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findById(long id);
}
This repository extends the JpaRepository
interface and adds a custom method findById
that returns a single User
object by its ID. With this repository in place, we can easily retrieve all users or a single user by ID using the provided methods.
Now, let's create a mapper class that maps a User
entity to a UserDTO
class that contains only the firstName
, secondName
, username
, and age
fields. We can use the MapStruct library to create this mapper class. Here's an example of the UserMapper
interface:
To use MapStruct in your Spring Boot project, you need to add the following dependency in your pom.xml
file:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.0.Final</version>
</dependency>
kotlinCopy codeimport org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
@Mapping(target = "firstName", source = "firstName")
@Mapping(target = "secondName", source = "secondName")
@Mapping(target = "username", source = "username")
@Mapping(target = "age", source = "age")
UserDTO userToUserDTO(User user);
}
This mapper class uses the @Mapper
annotation to mark this interface as a MapStruct mapper. The @Mapping
annotations specify which fields to map from the User
entity to the UserDTO
class.
Finally, we need to create a UserMapperService
class that provides a method to map a User
entity to a UserDTO
object using the `UserMapper
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserMapperService {
public UserDTO toUserDTO(User user) {
return UserMapper.INSTANCE.userToUserDTO(user);
}
public List<UserDTO> toUserDTOList(List<User> users) {
return users.stream().map(user -> toUserDTO(user)).collect(Collectors.toList());
}
}
The toUserDTOList
method takes a list of User
entities as input and maps each of them to a UserDTO
object using the toUserDTO
method. The result is a list of UserDTO
objects. This method is useful when you need to return multiple User
entities as multiple UserDTO
objects, for example, when retrieving a list of all users from the database.