Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a MapStruct mapper from Order (with Customer and a list of OrderLine entities) to OrderDto (customerName, lineCount, total). Make the build fail if a target field is not mapped, and explain how you test it.

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.

Java
@Entity
public class Order {
@Id private Long id;
@ManyToOne(fetch = FetchType.LAZY) private Customer customer;
@OneToMany(mappedBy = "order") private List<OrderLine> lines = new ArrayList<>(); // lazy by default
// getters
}
@Entity public class Customer { @Id private Long id; private String name; /* getters */ }
@Entity public class OrderLine {
@Id private Long id; @ManyToOne private Order order;
private BigDecimal unitPrice; private int quantity;
public BigDecimal amount() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
}
public record OrderDto(String customerName, int lineCount, BigDecimal total) { }

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.

XML
<!-- pom.xml -->
<dependency>
<groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>${mapstruct.version}</version>
</dependency>
...
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></path>
<path><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>${mapstruct.version}</version></path>
<path><groupId>org.projectlombok</groupId><artifactId>lombok-mapstruct-binding</artifactId><version>0.2.0</version></path>
</annotationProcessorPaths>
</configuration>
</plugin>
// Gradle equivalent
// implementation "org.mapstruct:mapstruct:$mapstructVersion"
// annotationProcessor "org.mapstruct:mapstruct-processor:$mapstructVersion"

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.

Java
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface OrderMapper {
@Mapping(target = "customerName", source = "customer.name")
@Mapping(target = "lineCount", expression = "java(order.getLines() == null ? 0 : order.getLines().size())")
@Mapping(target = "total", source = "lines", qualifiedByName = "sumLines")
OrderDto toDto(Order order);
@Named("sumLines")
default BigDecimal sumLines(List<OrderLine> lines) {
if (lines == null) return BigDecimal.ZERO;
return lines.stream().map(OrderLine::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
}
}

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.

Java
@Component
public class OrderMapperImpl implements OrderMapper {
@Override
public OrderDto toDto(Order order) {
if (order == null) return null;
String customerName = orderCustomerName(order); // null-safe: null if customer is null
BigDecimal total = sumLines(order.getLines());
int lineCount = order.getLines() == null ? 0 : order.getLines().size();
return new OrderDto(customerName, lineCount, total);
}
private String orderCustomerName(Order order) {
Customer customer = order.getCustomer();
if (customer == null) return null;
return customer.getName();
}
}
// Now add a field to the DTO: record OrderDto(String customerName, int lineCount, BigDecimal total, String status)
// mvn compile
// ERROR: Unmapped target property: "status".

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.

Java
@Query("select distinct o from Order o join fetch o.customer left join fetch o.lines where o.id in :ids")
List<Order> findWithCustomerAndLines(List<Long> ids); // one query for customer and lines
@Transactional(readOnly = true)
public List<OrderDto> summaries(List<Long> ids) {
return repo.findWithCustomerAndLines(ids).stream().map(mapper::toDto).toList();
}
Step throughMapping inside the transaction
ControllerOrderServiceRepositoryOrderMapper
summaries(ids)
begin read-only transaction
findWithCustomerAndLines(ids)
orders with customer and lines loaded, one query
toDto(order) for each
OrderDto list, no extra queries
DTOs, transaction committed

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.

Java
class OrderMapperTest {
private final OrderMapper mapper = Mappers.getMapper(OrderMapper.class);
@Test
void mapsNameCountAndTotal() {
Order order = anOrder(new Customer("Ada"), line("10.00", 2), line("2.50", 4));
OrderDto dto = mapper.toDto(order);
assertThat(dto).isEqualTo(new OrderDto("Ada", 2, new BigDecimal("30.00"))); // 20.00 + 10.00
}
@Test
void handlesMissingCustomerAndLines() {
Order order = anOrder(null); // no customer, empty lines
OrderDto dto = mapper.toDto(order);
assertThat(dto.customerName()).isNull();
assertThat(dto.lineCount()).isZero();
assertThat(dto.total()).isEqualByComparingTo("0");
}
}

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.

What to say in the interviewAbout 80 seconds aloud

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/