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
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:
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
.
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; } }
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; } }
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
.
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.
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.
Mapping Entity to DTO in Spring Boot with ModelMapper:
// 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);
Configuring ModelMapper for entity-to-DTO mapping in Spring Boot:
// 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; } }
Customizing field mappings with ModelMapper in Spring Boot:
// Custom field mapping in ModelMapper modelMapper.typeMap(User.class, UserDTO.class) .addMapping(src -> src.getId(), UserDTO::setUserId);
Handling nested objects and relationships with ModelMapper in Spring Boot:
// Handling nested objects in ModelMapper modelMapper.typeMap(Order.class, OrderDTO.class) .addMappings(mapper -> mapper.map(src -> src.getUser().getName(), OrderDTO::setUserName));
DTO to Entity mapping with ModelMapper in Spring Boot:
// DTO to Entity mapping in ModelMapper User userEntity = modelMapper.map(userDTO, User.class);
Conditional mapping and type conversion in ModelMapper for Spring Boot:
// 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); });
Error handling and validation in entity-to-DTO mapping with ModelMapper:
// Using Bean Validation with ModelMapper Set<ConstraintViolation<UserDTO>> violations = validator.validate(userDTO); if (!violations.isEmpty()) { // Handle validation errors }
Unit testing entity-to-DTO mapping with ModelMapper in Spring Boot:
// 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 }