Member-only story

Transfer DTO to Entity

Model Mapper

Swati Sinha
1 min readJul 6, 2023

Let’s first create a DTO class. We use the DTO class to avoid multiple calls from clients and we can pass the attributes specific to client’s request.

Photo by Mike Kenneally on Unsplash

Add model mapper dependency in POM file.

Create a method in Controller which will accept the DTO class as Request Body.

Create a Bean of Model Mapper in config class.

Create a DTO UserCreateRequest class which will be used as a request body .

Create a Entity class which will persist in the Database.

Create a method using Model mapper.

<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.2</version>
</dependency>
  @PostMapping("/user")
public ResponseEntity createUser(@RequestBody UserCreateRequest userCreateRequest)
@Bean
public ModelMapper modelMapper()
{
return new ModelMapper();
}
public class UserCreateRequest {
@NonNull
private String name;
@NonNull
private String phoneNumber;
@NonNull
private String email;
@NonNull
private String dob;
private String country;
}
@Entity
@Data
public class User {
Logger logger = LoggerFactory.getLogger(User.class);
@Id

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response

Model mapper.

Elegant solution ;) How does it scale? Do you have a guess?
I am considering it to test it in our high-priced projects with a lot of DTOs and entities--often "separated" by a service.