Quick revision
The short answer
We declare an interface annotated with @Mapper(componentModel = "spring") and describe the differences with @Mapping: id to orderId, customer.name to customerName, an expression for lineCount and a small conversion method for createdDate. MapStruct is an annotation processor, so at compile time it writes a plain Java class, OrderMapperImpl, that copies the fields with ordinary getter and constructor calls. Nothing happens by reflection at runtime, and mistakes such as an unmapped target field are reported by the build.
What to remember
In this answer, we wrote a MapStruct mapper for Order to OrderDto with @Mapping rules for a renamed field, a nested property, a computed count and a time zone conversion. We saw that MapStruct is an annotation processor that generates a plain Java implementation at compile time, so there is no runtime reflection and mistakes appear in the build, especially with unmappedTargetPolicy set to ERROR. Finally, we saw that Lombok users must declare both processors and the lombok-mapstruct-binding so that MapStruct sees the generated accessors.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We declare an interface annotated with @Mapper(componentModel = "spring") and describe the differences with @Mapping: id to orderId, customer.name to customerName, an expression for lineCount and a small conversion method for createdDate. MapStruct is an annotation processor, so at compile time it writes a plain Java class, OrderMapperImpl, that copies the fields with ordinary getter and constructor calls. Nothing happens by reflection at runtime, and mistakes such as an unmapped target field are reported by the build.
Why this question is asked
Mapping between entities and DTOs is some of the most repetitive code in a Spring service, and also a common source of small bugs: a field renamed in one class but not in the mapping, or a nested null that throws. MapStruct removes the typing while keeping the result visible and checked. Interviewers ask for this mapper because it touches the parts people get wrong: nested properties, computed fields, type conversions and the build setup. In this answer, we will set up the two records, write the mapper, read the code MapStruct generates, make the build fail on unmapped fields, and finish with the Lombok setup.
1The Source and Target Types
We start with the two types from the question. Order is a domain record with a nested Customer and a list of lines. OrderDto is what the API returns: the names differ, one field is computed, and the date has a different type.
Notice that none of the four target names matches a source name exactly, so MapStruct cannot map anything by convention here. That makes this a good example: every rule must be written down, and the build will tell us if we forget one. Records are supported as both source and target in recent MapStruct versions (1.4 and later): it reads record components through their accessor methods and builds the target through its canonical constructor.
2Writing the Mapper
A MapStruct mapper is an interface or abstract class with abstract mapping methods. Each @Mapping annotation describes one target property that does not follow the default rule of copying a source property with the same name.
componentModel = "spring" makes the generated class a Spring bean, so we inject OrderMapper like any other dependency. The dotted source customer.name walks into the nested record, and MapStruct generates a null check for customer on the way. The expression is copied into the generated code as Java, which is why it is written inside java(...); it is not checked until the generated class compiles, so we keep expressions short. For the date, Instant to LocalDate needs a decision about the time zone, so we write that decision once in a named method. If createdDate were a String, we could instead write dateFormat = "yyyy-MM-dd", which MapStruct applies when converting between dates and strings.
3What MapStruct Generates and When
MapStruct is an annotation processor: a plugin that the Java compiler runs while compiling our code. When javac sees @Mapper, it hands the interface to MapStruct, which reads the types, works out every property and writes a new source file. javac then compiles that file together with the rest of the project. The output lands in target/generated-sources/annotations with Maven, or build/generated/sources/annotationProcessor with Gradle.
- javac compiles OrderMapperfinds
@Mapper - MapStruct processor runsreads Order and
OrderDto - Every target property mapped?YesWrite OrderMapperImpl.javaNoReport error, build fails
- javac compiles the generated classsame build step
- Spring finds the @Component at startupinjected like any bean
5 steps in order. Play them, or step through them one at a time.
All checking happens during the build; nothing is discovered at runtime.
Notice that this is exactly the code we would have written by hand: accessor calls, null checks and a constructor call. There is no reflection and no runtime library doing the copying, so it is as fast as hand-written code, and we can set a breakpoint in it while debugging. The time spent is at compile time, and only for files that changed.
4Failing the Build on Unmapped Fields
By default, if a target property has no source and no rule, MapStruct prints a warning such as Unmapped target property: "createdDate" and leaves the property empty. Warnings are easy to miss in a long build log, and an empty field in an API response is a real bug. Setting unmappedTargetPolicy = ReportingPolicy.ERROR, as in our mapper, turns that warning into a compile error.
Rather than repeating it on every mapper, we can set it once for the project through a compiler argument, -Amapstruct.unmappedTargetPolicy=ERROR, or with a shared @MapperConfig that every mapper references. Now if somebody adds a currency field to OrderDto and forgets the mapping, the build fails and names the field. Target properties we really want to leave empty are marked explicitly with @Mapping(target = "x", ignore = true), which also documents the intention.
5Using MapStruct Together With Lombok
Many projects also use Lombok, which generates getters, setters and builders during compilation. Both are annotation processors, and MapStruct needs to see the getters that Lombok creates. If MapStruct runs first, it sees classes without accessors and reports unmapped properties that do exist. The fix is to declare both processors, plus the small lombok-mapstruct-binding processor that tells them how to cooperate.
Declaring the processors explicitly is good practice anyway. Recent JDKs no longer run annotation processors that are merely found on the classpath unless told to, so relying on implicit discovery can silently skip MapStruct after a JDK upgrade; check your JDK's javac notes.
6Follow-up questions
How does MapStruct handle a nested collection, such as List<OrderLine> to List<OrderLineDto>?
If we declare a method OrderLineDto toDto(OrderLine line) in the same mapper, MapStruct uses it automatically for each element and generates the loop that builds the new list. We can also reference other mappers through the uses attribute of @Mapper, so line mapping can live in its own class.
Can MapStruct update an existing object instead of creating a new one?
Yes. A method with a second parameter annotated @MappingTarget, such as void update(OrderDto dto, @MappingTarget OrderEntity entity), copies values onto the existing object. This is useful for applying a request to a JPA entity, but it does not work with records, which are immutable.
Why prefer a named method over an expression for createdDate?
A named method is ordinary Java: the compiler checks it, an IDE refactors it and a unit test can call it directly. An expression is a string that MapStruct pastes into generated code, so a typo shows up only as an error in a generated file. Expressions are fine for one-liners; anything with a decision, like a time zone, deserves a method.
7Conclusion
In this answer, we wrote a MapStruct mapper for Order to OrderDto with @Mapping rules for a renamed field, a nested property, a computed count and a time zone conversion. We saw that MapStruct is an annotation processor that generates a plain Java implementation at compile time, so there is no runtime reflection and mistakes appear in the build, especially with unmappedTargetPolicy set to ERROR. Finally, we saw that Lombok users must declare both processors and the lombok-mapstruct-binding so that MapStruct sees the generated accessors.
Open with
I would write an interface annotated @Mapper with componentModel spring, so the implementation becomes a Spring bean I can inject. On the toDto method I add a @Mapping for each difference: target orderId from source id, customerName from customer.name, which walks the nested object with a null check, lineCount with a short expression, java order.lines().size() guarded for null, and createdDate from createdAt through a named default method that converts the Instant to a LocalDate in UTC, because that time zone decision should be explicit.
Then, if they want more
If the target were a String I could use dateFormat instead. MapStruct is an annotation processor, so when javac compiles the interface it generates OrderMapperImpl as a normal Java source file, with plain accessor calls, null checks and a constructor call for the record.
There is no reflection at runtime, it is as fast as hand-written code and I can debug it. By default an unmapped target field only produces a warning, so I set unmappedTargetPolicy to ReportingPolicy.ERROR, preferably project-wide through a compiler argument or a shared MapperConfig, so a forgotten field fails the build. Records work as source and target in recent versions.
And if the project uses Lombok, I declare lombok, the MapStruct processor and lombok-mapstruct-binding in annotationProcessorPaths so MapStruct sees Lombok's getters.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a MapStruct mapper from Order(id, customer, lines, createdAt) to OrderDto(orderId...": https://scrivio-interview-library.netlify.app/java/utility-libraries/c947a40461/