Question
What is the process for mapping nested collections in MapStruct?
@Mapping(target = "items", source = "nestedCollection.items")
List<ItemDto> mapItems(List<NestedItem> nestedItems);
Answer
Mapping nested collections in MapStruct can be straightforward once you understand the structure of your source and target objects. MapStruct provides annotations that facilitate the mapping of complex types without the need for boilerplate code. Below is a detailed breakdown of how to achieve this effectively.
@Mapper
public interface ItemMapper {
@Mapping(target = "items", source = "nestedCollection.items")
ItemDto toDto(NestedCollection nestedCollection);
// Custom mapping for nested item
NestedItemDto mapItems(NestedItem nestedItem);
}
Causes
- Mismatch between source and target field names that needs to be addressed via annotations.
- Inconsistent types between nested collections may lead to mapping failures. Ensure that the data types align properly.
Solutions
- Use the @Mapping annotation to specify how to map nested attributes. For instance, indicate the source path using the 'source' property.
- If nested objects require mapping to different types, create custom mapping methods to handle those conversions.
Common Mistakes
Mistake: Forgetting to specify the source or target for nested mappings.
Solution: Always use the @Mapping annotation to clearly indicate the source and target properties.
Mistake: Using an incompatible type between source and target collections.
Solution: Ensure that the types of the nested collections match and are compatible with each other to avoid ClassCastExceptions.
Helpers
- MapStruct
- nested collections mapping
- MapStruct examples
- Java mapping
- Java collections
- MapStruct tutorial