Spring Boot - Map Entity to DTO using ModelMapper

Last Updated : 29 Apr, 2026

In Spring Boot, ModelMapper is a library used to automatically map data between Entity objects and DTO (Data Transfer Object) classes. It simplifies the process of converting objects by reducing the need for manual mapping code. This helps keep the application clean, maintainable, and secure by controlling the data sent between layers.

  • Supports custom mappings and configuration for complex object transformations.
  • Improves performance and readability by avoiding repetitive setter/getter logic.
  • Enhances data security by exposing only required fields through DTOs.

DTO

A DTO (Data Transfer Object) is a simple Java class used to transfer data between layers of an application without exposing the internal entity structure.

  • Helps hide sensitive fields (e.g., password) from being exposed in API responses.
  • Allows developers to selectively expose only required data to the web layer.

Syntax:

Java
public class Geeks{

    private DataType field1;
    private DataType field2;
    private DataType field3;

    // Getter
    public DataType getField1() {
        return field1;
    }

    // Setter
    public void setField1(DataType field1) {
        this.field1 = field1;
    }
}

Step By Step Implementation

Step 1: Create Spring Boot Project

Create a Spring Boot project using an IDE like Eclipse or IntelliJ.

  • Use Spring Initializr to generate the project.
  • Add required dependencies like Spring Web, Spring Data JPA, MySQL Driver .
  • Import the project into the IDE.
Fig 1 - Add Dependency

Step 2: Add ModelMapper Dependency

Add the ModelMapper dependency in the pom.xml file to enable automatic mapping between Entity and DTO.

Syntax:

<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>

Step 3: Create Database Schema

Create a database schema in MySQL to store application data.

  • Open MySQL Workbench.
  • Go to Schemas -> Right Click -> Create Schema.
  • Enter schema name model_mapper_db and click Apply.
Fig 2 - Create SchemaFig 3 - DB Schema Name

Once, we add the name of our schema, we need to click on Apply button, it will pop up one more window where we need to click again on Apply button. This will create our schema.

Fig 4 - Database Schema

Step 4: Configure Database

Configure database connection properties in application.properties.

Syntax:

server.port=9090
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/model_mapper_db
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Run the application to check whether the database is configured correctly. Go to the main class (ModelMapperApplication.java) and select Right Click -> Run As -> Java Application.

Fig 5 - Run Application

Once, we run our application as Java Application, we can see in the console that our application is started and set up the connection to the database.

Fig 6 - DB Connection Setup

Step 5: Create Entity Class

Create an Entity class representing the database table.
For our application, we will be using the User class as our entity class. It will have the following fields id, name, email, and password.

User.java

Java
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user-id")
    private int id;
    @Column(name="user-name")
    private String name;
    @Column(name="user-email")
    private String email;
    @Column(name="user-password")
    private String password;
    
    // NoArgsConstructor
    public User() {
        super();
    }
    // Getters & Setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}

Once, we have written our entity class. We will run our application, As we have done the database configuration, JPA will create the User table in the database automatically using the annotation we have added to our entity class.

Fig 7 - User Table

Step 6: Create a User Repository

Create an interface and name it as UserRepository and extends this class to the JPA repository. So, we can have CRUD operations easily available.

UserRepository.java

Java
import org.springframework.data.jpa.repository.JpaRepository;

import com.geeksforgeeks.ModelMapper.data.User;

// In the arguments we need to pass our model class and 
// the second argument is the type of id we have used 
// in our model class
public interface UserRepository extends JpaRepository<User, Integer> {

}

Step 7: Create User Service

Now, we will create a service interface and name it as UserService. We will add only two methods to it. One to add the user and the other to get the user.

UserService.java

Java
import com.geeksforgeeks.ModelMapper.data.User;

public interface UserService {
    
    public User createUser(User user);
    public User getUser(int userId);

}

Step 8: Create Service Interface

UserServiceImpl.java

Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geeksforgeeks.ModelMapper.data.User;
import com.geeksforgeeks.ModelMapper.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Override
    public User createUser(User user) {
        User userSavedToDB = this.userRepository.save(user);
        return userSavedToDB;
    }

    @Override
    public User getUser(int userId) {
        User user = this.userRepository.getById(userId);
        return user;
    }

}

Step 9: Create a Controller

In this step, we will create a user controller for handling and mapping our request.

UserController.java

Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.geeksforgeeks.ModelMapper.data.User;
import com.geeksforgeeks.ModelMapper.service.UserService;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @GetMapping("/{userId}")
    public User getUser(@PathVariable int userId) {
        return userService.getUser(userId);
    }
}

Step 10: Run the Application

In this step, we will run our application and test restful services using postman.

1. CREATE A USER:

Fig 8 - Create Request

Once, we send our request. We will get the following output.

Fig 9 - Response

We can also check our database for new user entries.

Fig 10 - User Added To DB

2. GET A USER:

We will be using the GET endpoint and userid to retrieve users from the database.

Fig 11 - Get A User

As we can see in the above response, we will also receive passwords which is not a good practice to write restful APIs. To overcome this problem, we will use DTO.

Step 11: Create DTO

Create UserDTO class that will contain only those fields that are required and necessary for the web layer.

UserDto.java

Java
public class UserDto {
    
    private String name;
    private String email;
    
    // NoArgsConstructor
    public UserDto() {
        super();
    }
  
    // Getters & Setters
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

Step 12: Adding Model Mapper Dependency

We need to add the following dependency in our pom.xml file.

<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>

Step 13: Modify Classes

Now, to use UserDto, we need to modify our UserService, UserServiceImpl, and UserController class.

UserService.java

Java
import com.geeksforgeeks.ModelMapper.data.User;
import com.geeksforgeeks.ModelMapper.dto.UserDto;

public interface UserService {
    
    public User createUser(User user);
  
    // updated it with UserDto
    public UserDto getUser(int userId);

}

UserServiceImpl.java

Java
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geeksforgeeks.ModelMapper.data.User;
import com.geeksforgeeks.ModelMapper.dto.UserDto;
import com.geeksforgeeks.ModelMapper.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ModelMapper modelMapper;
    
    @Override
    public User createUser(User user) {
        User userSavedToDB = this.userRepository.save(user);
        return userSavedToDB;
    }

    // update it with UserDto
    @Override
    public UserDto getUser(int userId) {
        User user = this.userRepository.findById(userId).get();
        UserDto userDto = this.modelMapper.map(user, UserDto.class);
        return userDto;
    }

}

UserController.java

Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.geeksforgeeks.ModelMapper.data.User;
import com.geeksforgeeks.ModelMapper.dto.UserDto;
import com.geeksforgeeks.ModelMapper.service.UserServiceImpl;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserServiceImpl userServiceImpl;
    
    @PostMapping("/create")
    public ResponseEntity<User> createUser(@RequestBody User user){
        User userCreated = this.userServiceImpl.createUser(user);
        return new ResponseEntity<User>(userCreated, HttpStatus.CREATED);
    }
    
    // update it with UserDto
    @GetMapping("/get/{id}")
    public ResponseEntity<UserDto> getUser(@PathVariable("id") int userId){
        UserDto userDto = this.userServiceImpl.getUser(userId);
        return new ResponseEntity<UserDto>(userDto, HttpStatus.OK);
    }

}

Step 14: Add Model Mapper Bean

In this step, we will add model mapper bean to our main spring boot class.

Java
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ModelMapperApplication {

    public static void main(String[] args) {
        SpringApplication.run(ModelMapperApplication.class, args);
    }
    
    @Bean
    public ModelMapper getModelMapper() {
        return new ModelMapper();
    }

}

Step 15: Run the Application

Now, we will again run our application and use the GET endpoint to see the response.

Fig 12 - Response

The response now contains only the required fields for the web layer. Although the User is created with all fields, only the necessary fields are returned in the response.

Comment