Quick revision
The short answer
We declare an interface annotated with @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR), map customerName from customer.name, lineCount from the size of lines and total with a default method that sums line amounts with BigDecimal, and configure mapstruct-processor as an annotation processor, plus lombok-mapstruct-binding if Lombok is used. ReportingPolicy.ERROR makes any unmapped target field a compile error. Because reading customer and lines may trigger lazy loading, we map inside the transaction or fetch them with a join fetch or projection, and we test the mapper with a plain unit test, including null nested objects.
What to remember
In this answer, we wrote a MapStruct mapper from Order to OrderDto. We configured mapstruct-processor, and lombok-mapstruct-binding with Lombok, as annotation processors, declared the mapper with componentModel spring and unmappedTargetPolicy ERROR so any unmapped target fails compilation, mapped customerName from customer.name, lineCount with a null-safe expression and total with a named BigDecimal default method. We kept pricing rules out of the mapper, mapped inside a transaction after a join fetch to avoid lazy loading, and tested the mapper with Mappers.getMapper, including null nested objects.
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", unmappedTargetPolicy = ReportingPolicy.ERROR), map customerName from customer.name, lineCount from the size of lines and total with a default method that sums line amounts with BigDecimal, and configure mapstruct-processor as an annotation processor, plus lombok-mapstruct-binding if Lombok is used. ReportingPolicy.ERROR makes any unmapped target field a compile error. Because reading customer and lines may trigger lazy loading, we map inside the transaction or fetch them with a join fetch or projection, and we test the mapper with a plain unit test, including null nested objects.
Background to this question
MapStruct is the most common way to remove hand-written mapping code from Spring services without giving up type safety. This coding question checks several things at once: whether we know the annotations, whether we can make the build protect us from forgotten fields, whether we keep business logic out of mappers, and whether we remember that mapping entities can quietly trigger database queries. In this answer, we will set up the build, write the mapper, look at the generated code, handle the total, deal with lazy loading, and write the tests.
1The Model We Are Mapping
We have an Order entity with a many-to-one Customer and a one-to-many list of OrderLine entities. The target is a flat OrderDto with three fields.
Notice that OrderDto is a record. MapStruct 1.5 and later map records through their canonical constructor, so we do not need setters on the DTO.
2Configuring the Annotation Processor
MapStruct generates code during compilation, so the processor must be on the annotation processor path. In Maven, that is the compiler plugin configuration. If the project uses Lombok, the order matters: MapStruct needs to see the getters Lombok generates, so we add lombok-mapstruct-binding as well.
Use the current MapStruct 1.6.x release and check the binding version against your Lombok version. A common symptom of a missing processor is a NoSuchBeanDefinitionException for OrderMapper at startup, because no implementation was generated.
3Writing the Mapper
Now the mapper. componentModel = "spring" makes the generated class a Spring bean we can inject, and unmappedTargetPolicy = ReportingPolicy.ERROR turns every unmapped target property into a compile error.
source = "customer.name" tells MapStruct to navigate a nested property. The expression for lineCount is Java code copied into the generated method, so we write the null check ourselves. total uses a named default method that MapStruct calls with order.getLines().
4What MapStruct Generates and How the Build Fails
Looking at the generated class, under target/generated-sources/annotations, is the best way to understand MapStruct. It is plain code.
So the build fails the moment the DTO gains a field that nobody mapped, which is exactly what the question asks for. The exact error text may vary slightly between MapStruct versions.
5Keeping Business Logic Out and Watching Lazy Loading
Summing line amounts is borderline business logic. Here it is simple and the result is only for display, so a default method is acceptable. But if the total involved discounts, tax or rounding rules, it belongs on the Order itself, as order.total(), and the mapper would map it with source = "total". Mappers should copy and reshape data, not decide prices, because rules in mappers get duplicated and are not tested as business rules.
The other catch is lazy loading. customer is LAZY and lines is a lazy collection, so calling toDto touches the database. Outside a transaction with Open Session in View off, that throws LazyInitializationException; inside one, mapping a list of 100 orders runs about 200 extra queries. So we map inside the service transaction and fetch what the DTO needs in the query.
7 messages in order. Play them, or step through them one at a time.
The mapper only touches data that is already loaded.
6Testing the Mapper
Because the generated mapper is plain code, the quickest test needs no Spring at all. Mappers.getMapper returns an instance of the generated implementation. We cover the normal case and the null nested objects.
Notice the BigDecimal comparison. new BigDecimal("30.00") equals the sum because both have scale 2, but BigDecimal.equals compares scale as well as value, so for totals with uncertain scale isEqualByComparingTo is safer. Mappers.getMapper works even with componentModel spring, because the generated class has a public no-argument constructor when it has no injected dependencies; mappers that use other mappers are better tested as Spring beans with a small @SpringJUnitConfig test.
7Follow-up questions
When would a JPA projection or a record query be better than mapping entities?
When the endpoint only reads data. A constructor expression such as select new com.acme.OrderSummary(c.name, size(o.lines), sum(l.unitPrice * l.quantity)) or a Spring Data interface projection selects exactly the columns the DTO needs in one query, loads no entities into the persistence context, cannot trigger lazy loading and needs no mapper. Mapping entities is better when we load them anyway to change them, or when the DTO needs logic that lives on the entity.
Why not use expression for total too?
We could, but expressions are Java code inside a string, so the IDE cannot refactor or check them well, and errors show up only in generated code. A named default method is real Java that the compiler and IDE understand, and it can be tested directly.
8Conclusion
In this answer, we wrote a MapStruct mapper from Order to OrderDto. We configured mapstruct-processor, and lombok-mapstruct-binding with Lombok, as annotation processors, declared the mapper with componentModel spring and unmappedTargetPolicy ERROR so any unmapped target fails compilation, mapped customerName from customer.name, lineCount with a null-safe expression and total with a named BigDecimal default method. We kept pricing rules out of the mapper, mapped inside a transaction after a join fetch to avoid lazy loading, and tested the mapper with Mappers.getMapper, including null nested objects.
Open with
I would write an interface annotated with @Mapper, with componentModel spring so the generated implementation is a bean, and unmappedTargetPolicy set to ReportingPolicy.ERROR, which makes any target field without a mapping a compile error.
Then, if they want more
The method toDto takes an Order. For customerName I use @Mapping with source customer.name, and MapStruct generates a null-safe nested getter. For lineCount I use an expression with order.getLines().size() and a null check. For total I use source lines with qualifiedByName pointing at a default method that streams the lines and sums their amounts with BigDecimal add, starting from ZERO.
If the total involved discounts or tax, I would put that on the Order and just map it, because mappers should not hold business rules. In the build I add mapstruct-processor to the annotation processor path, and lombok-mapstruct-binding if we use Lombok so MapStruct sees the generated getters.
One thing to watch: customer and lines are lazy, so I call the mapper inside the service transaction and load them with a join fetch, otherwise I get LazyInitializationException or N+1 queries.
For tests, I use Mappers.getMapper in a plain unit test, check the normal case with a known total, and check a null customer and empty lines, comparing BigDecimal with compareTo semantics.
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 (with Customer and a list of OrderLine entities) to...": https://scrivio-interview-library.netlify.app/java/application-architecture/10b2fb9a4b/