Performance: MapStruct for automatic mapping
This affects the backend processing speed and indirectly impacts frontend load by reducing server response time.
Jump into concepts and practice - no test required
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
UserDTO userToUserDTO(User user);
}public UserDTO mapToDto(User user) {
UserDTO dto = new UserDTO();
dto.setId(user.getId());
dto.setName(user.getName());
dto.setEmail(user.getEmail());
// many more fields mapped manually
return dto;
}| Pattern | CPU Usage | Response Time Impact | Code Maintainability | Verdict |
|---|---|---|---|---|
| Manual mapping | High CPU usage due to repetitive code | Increases response time by milliseconds | Harder to maintain and error-prone | [X] Bad |
| MapStruct automatic mapping | Low CPU usage with generated code | Reduces response time improving LCP | Easy to maintain and less error-prone | [OK] Good |
MapStruct in a Spring Boot application?@Mapper to mark interfaces for automatic mapping generation.@Mapper(componentModel = "spring")
public interface UserMapper {
UserDto toDto(User user);
}UserMapper in a Spring Boot service and call toDto(user)?@Mapper
public interface ProductMapper {
ProductDto toDto(Product product);
}ProductMapper in a Spring Boot service, you get an error. What is the likely cause?componentModel = "spring", MapStruct does not create a Spring bean for the mapper.public class Employee {
private String name;
private int age;
private String department;
// getters and setters
}
public class EmployeeDto {
private String name;
private int age;
// getters and setters
}Employee to EmployeeDto using MapStruct but ignore the department field. Which mapper method signature and annotation is correct?@Mapping(target = "fieldName", ignore = true) on the method.componentModel = "spring" allows Spring to manage the mapper bean automatically.