Custom Methods for Complex Transformations
In real-world applications, object mapping often goes beyond simple field-to-field assignments. When you need to apply custom logic—such as combining multiple fields, formatting values, or conditionally mapping—you can use custom methods.
For example, in MapStruct, you can define a method like:
default String mapFullName(String firstName, String lastName) {
return firstName + " " + lastName;
}
Then use it in your mapper to transform source fields accordingly.
Handling Nested Objects
Mapping nested structures requires mapping from one object hierarchy to another. MapStruct supports this through recursive mapping strategies. Consider this example:
class Address {
private String street;
private String city;
}
class UserDTO {
private String street;
private String city;
}
You can map UserDTO
to Address
by defining a method that extracts nested fields or by allowing MapStruct to auto-navigate the hierarchy if the structure aligns.
Dealing with Different Field Names
When source and target field names differ, you can use the @Mapping
annotation to explicitly specify the mapping:
@Mapping(source = "firstName", target = "name")
User map(UserDTO dto);
This tells the mapper to take the firstName
from the source and place it in the name
field of the target object. This is critical when working with legacy systems or external APIs.
Type Conversions
Sometimes, field types don't match directly, such as String
to Date
or String
to enum
. You can define custom converters for these scenarios.
default LocalDate map(String dateStr) {
return LocalDate.parse(dateStr, DateTimeFormatter.ISO_DATE);
}
For enums:
enum Status { ACTIVE, INACTIVE }
default Status map(String status) {
return Status.valueOf(status.toUpperCase());
}
MapStruct also allows integration with external mappers for more complex conversions.
Conclusion
Advanced mapping requires flexibility and control. By leveraging custom methods, nested object handling, annotated field mappings, and type converters, you can handle even the most complex transformation scenarios with clarity and precision.
0 Comments