Java / MapStruct Java Interview questions part 2
How do you handle multiple mapping methods for the same source and target types?
If a mapper declares more than one method with an identical source and target type signature, MapStruct's normal automatic resolution becomes ambiguous - it has no way to know which one a given nested property mapping should use, and this typically surfaces as a compile-time ambiguity error at the call site that needed the conversion.
The fix is to make the intended method explicit at the point of use rather than relying on automatic matching:
- Annotate each candidate method with
@Named("someLabel"). - At the
@Mappingthat needs one specific variant, addqualifiedByName = "someLabel".
@Named("short") String toShortLabel(Status status); @Named("full") String toFullLabel(Status status); @Mapping(target = "label", qualifiedByName = "full") StatusDto toDto(Status status);
This pattern is common when the same types need different string formats or summary levels depending on where the mapping is used, without needing entirely separate mapper interfaces for each variant.
More Related questions...