Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - Map Entity to DTO using ModelMapper

Using ModelMapper with Spring Boot is an efficient way to map between your entity objects and DTOs (Data Transfer Objects). ModelMapper offers property matching strategies, type converters, and more to handle complex object-to-object mapping.

Here's a step-by-step guide to integrating ModelMapper with Spring Boot:

1. Add the dependency:

Include the modelmapper dependency in your pom.xml:

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

Note: Ensure that you are using the latest version of modelmapper.

2. Configure ModelMapper Bean:

Define a ModelMapper bean in a configuration class. This makes it available for autowiring throughout your Spring Boot application.

@Configuration
public class AppConfiguration {

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper;
    }
}

3. Use ModelMapper:

Suppose you have an entity User:

@Entity
public class User {
    private Long id;
    private String username;
    private String email;
    // ... getters and setters
}

And a DTO UserDTO:

public class UserDTO {
    private Long id;
    private String username;
    private String email;
    // ... getters and setters
}

Map from User to UserDTO using ModelMapper:

@Service
public class UserService {

    @Autowired
    private ModelMapper modelMapper;

    public UserDTO convertToDTO(User user) {
        UserDTO userDTO = modelMapper.map(user, UserDTO.class);
        return userDTO;
    }

    public User convertToEntity(UserDTO userDTO) {
        User user = modelMapper.map(userDTO, User.class);
        return user;
    }
}

4. Advanced Mappings:

For scenarios where default mapping behavior isn't enough, ModelMapper provides APIs for customizing mappings:

modelMapper.typeMap(User.class, UserDTO.class)
    .addMappings(mapper -> {
        mapper.map(User::getUsername, UserDTO::setUserNameAlias);
    });

In the above example, a custom mapping is set to map the username property from User to a different property called userNameAlias in UserDTO.

5. Handling Nested and Complex Mappings:

ModelMapper can also handle nested and complex object mappings. If your entities have nested objects, ModelMapper will try its best to map nested properties based on their names.

Conclusion:

ModelMapper simplifies the often tedious task of mapping objects, especially in scenarios where you need to convert between entity and DTO objects. Integrating it with Spring Boot further enhances its utility by providing easy dependency management and configuration.

  1. Mapping Entity to DTO in Spring Boot with ModelMapper:

    • Description: Entity-to-DTO mapping is a common task in Spring Boot applications to separate the data model from the presentation layer.
    • Code:
      // Example Entity
      @Entity
      public class User {
          private Long id;
          private String username;
          private String email;
          // getters and setters
      }
      
      // Example DTO
      public class UserDTO {
          private String username;
          private String email;
          // getters and setters
      }
      
      // Using ModelMapper for mapping
      ModelMapper modelMapper = new ModelMapper();
      UserDTO userDTO = modelMapper.map(userEntity, UserDTO.class);
      
  2. Configuring ModelMapper for entity-to-DTO mapping in Spring Boot:

    • Description: Configuring ModelMapper involves setting up rules and behaviors for mapping entities to DTOs, ensuring consistency and flexibility.
    • Code:
      // Configuring ModelMapper in a Spring Boot configuration class
      @Configuration
      public class ModelMapperConfig {
          @Bean
          public ModelMapper modelMapper() {
              ModelMapper modelMapper = new ModelMapper();
              // Custom configurations if needed
              return modelMapper;
          }
      }
      
  3. Customizing field mappings with ModelMapper in Spring Boot:

    • Description: ModelMapper allows customizing field mappings, especially useful when the entity and DTO field names don't match.
    • Code:
      // Custom field mapping in ModelMapper
      modelMapper.typeMap(User.class, UserDTO.class)
                  .addMapping(src -> src.getId(), UserDTO::setUserId);
      
  4. Handling nested objects and relationships with ModelMapper in Spring Boot:

    • Description: ModelMapper can handle nested objects and relationships by recursively mapping the associated entities.
    • Code:
      // Handling nested objects in ModelMapper
      modelMapper.typeMap(Order.class, OrderDTO.class)
                  .addMappings(mapper -> mapper.map(src -> src.getUser().getName(), OrderDTO::setUserName));
      
  5. DTO to Entity mapping with ModelMapper in Spring Boot:

    • Description: In addition to entity-to-DTO mapping, ModelMapper can be used for DTO-to-entity mapping to handle updates or creation.
    • Code:
      // DTO to Entity mapping in ModelMapper
      User userEntity = modelMapper.map(userDTO, User.class);
      
  6. Conditional mapping and type conversion in ModelMapper for Spring Boot:

    • Description: ModelMapper supports conditional mappings and type conversion, enabling more fine-grained control over the mapping process.
    • Code:
      // Conditional mapping in ModelMapper
      modelMapper.typeMap(User.class, UserDTO.class)
                  .addMappings(mapper -> {
                      mapper.when(ctx -> ctx.getSource() != null)
                            .map(src -> src.getUsername().toUpperCase(), UserDTO::setUsername);
                  });
      
  7. Error handling and validation in entity-to-DTO mapping with ModelMapper:

    • Description: ModelMapper itself doesn't handle validation, but you can integrate it with validation frameworks like Bean Validation for error handling.
    • Code:
      // Using Bean Validation with ModelMapper
      Set<ConstraintViolation<UserDTO>> violations = validator.validate(userDTO);
      if (!violations.isEmpty()) {
          // Handle validation errors
      }
      
  8. Unit testing entity-to-DTO mapping with ModelMapper in Spring Boot:

    • Description: Unit testing the mapping process ensures that it works as expected, and ModelMapper provides a clean API for this purpose.
    • Code:
      // Unit testing entity-to-DTO mapping with JUnit
      @Test
      public void testEntityToDTOMapping() {
          User userEntity = // create entity
          UserDTO userDTO = modelMapper.map(userEntity, UserDTO.class);
          // Assert expected values
      }