Java / MapStruct Java Interview questions part 2
How do you map fields with different names using MapStruct?
When the source and target property names don't match, MapStruct won't map them automatically, so you point one to the other explicitly with @Mapping's source and target attributes.
@Mapper public interface EmployeeMapper { @Mapping(source = "empName", target = "name") @Mapping(source = "empId", target = "id") EmployeeDto toDto(Employee employee); }
You can also reach into nested properties using dot notation, for example source = "address.city", and MapStruct will generate the necessary null-safe chained getter calls. This saves you from writing a series of manual null checks just to pull one value out of a chain of nested objects.
More Related questions...