Java / MapStruct Java Interview questions part 2
How do you use @InheritInverseConfiguration for bidirectional mapping?
When two methods map the same pair of types in opposite directions, @InheritInverseConfiguration lets the reverse method automatically pick up the mirrored version of the forward method's @Mapping rules, instead of duplicating and re-negating them by hand.
@Mapper public interface PersonMapper { @Mapping(source = "fullName", target = "name") PersonDto toDto(Person person); @InheritInverseConfiguration Person toEntity(PersonDto dto); }
Here, toEntity automatically maps dto.name back to person.fullName because MapStruct inverts the source/target pairing declared on toDto. It won't invert an ignore rule the same way an unrelated round-trip would need, so any asymmetric rules (like an ignored audit field only relevant in one direction) should still be declared explicitly on the reverse method.
This pairing is most valuable on mappers with several renamed or reformatted properties, since without it a change to the forward method's @Mapping rules would need a matching manual edit on the reverse method to avoid the two drifting out of sync over time.
More Related questions...