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…

--

--

Responses (1)