Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 66 ยท Building REST APIs

DTO Mapping with MapStruct and ModelMapper

Why REST APIs use DTOs, how to map entities by hand, with MapStruct or with ModelMapper, how to handle nested objects, collections and partial updates, and the pitfalls.

Your JPA entities describe how data is stored. Your API describes how data is exchanged. These two shapes drift apart quickly: the entity has a password hash, a version column and a lazy collection, while the client wants a name, a price and a link. A DTO (data transfer object) is a small class, usually a Java record, that describes exactly the JSON you promise to clients. Something then has to copy data between entity and DTO. That "something" is a mapper.

This lesson explains why you want the separation, shows the three common ways to write mappers (by hand, MapStruct, ModelMapper), and covers the parts that cause real bugs: nested objects, collections, partial updates and fields that silently stay null. Spring Boot is not needed to run the idea, so the runnable examples are plain Java; the MapStruct and ModelMapper code is read-only because those libraries are not on this site's runner.

Why not return the entity?

Returning an entity straight from a controller is tempting, and it fails in predictable ways:

  • Leaks. Every field you add to the entity (an internal note, a password hash) appears in the JSON until someone notices.
  • Coupling. Renaming a column changes your public API. A client you cannot update breaks.
  • Lazy-loading surprises. Jackson walks the object graph while the response is written. A lazy association triggers queries at that moment, or throws LazyInitializationException, or follows a bidirectional link forever.
  • Mass assignment. If clients can send the entity back in a POST, they can set fields you never meant to expose, such as role or id. See Request and Response Bodies.

Separate request DTOs (what clients may send, with validation annotations) from response DTOs (what you promise to return). They often differ: a request has no id, a response has no password.

Java
public record BookRequest(
    @NotBlank String title,
    @Positive int priceInCents,
    @NotNull Long authorId) {}

public record BookResponse(long id, String title, String price, String authorName) {}

Not every project needs DTOs for everything. For a tiny internal tool, returning a simple projection is fine. As soon as the API has outside clients, the DTO layer pays for itself.

Option 1: map by hand

The simplest mapper is a class with plain methods. It is verbose, but it is explicit, needs no library, and the compiler checks every field.

Java A hand-written mapper with nested objects and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The conversion cents -> "$24.95" is a good reminder that mapping is not only copying: it applies business formatting. That logic belongs in the mapper (or in a small value type), not in the entity.

By-hand mappers scale poorly in one way: a DTO with thirty fields means thirty lines per direction, and a new field is easy to forget. That is the problem the two libraries solve.

Option 2: MapStruct (generated at compile time)

MapStruct is an annotation processor. You write an interface; at build time MapStruct generates a class that implements it with plain getter/setter or constructor calls. There is no reflection at run time, so it is fast, and an unmappable field becomes a compile-time warning or error.

XML
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>${mapstruct.version}</version>
</dependency>
<!-- plus the mapstruct-processor in maven-compiler-plugin annotationProcessorPaths -->
Java
@Mapper(componentModel = "spring", uses = AuthorMapper.class)
public interface BookMapper {

    @Mapping(source = "author.name", target = "authorName")
    @Mapping(source = "priceInCents", target = "price", qualifiedByName = "money")
    BookResponse toResponse(Book book);

    List<BookResponse> toResponses(List<Book> books);      // loops over toResponse for you

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "author", ignore = true)
    Book toEntity(BookRequest request);

    @Named("money")
    default String money(int cents) {
        return "$" + cents / 100 + "." + String.format("%02d", cents % 100);
    }

    // update an existing entity in place, skipping null fields in the request
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void update(BookPatch patch, @MappingTarget Book book);
}

Key ideas:

  • componentModel = "spring" makes the generated class a Spring bean, so you inject BookMapper like any service (Stereotype Annotations).
  • Fields with the same name map automatically. @Mapping handles renames, nested sources (author.name) and ignore.
  • A List<Book> to List<BookResponse> method is generated from the single-item method. Nested objects use another mapper listed in uses, or MapStruct generates a helper.
  • @MappingTarget updates an existing object, which is the right tool for PATCH.
  • By default MapStruct warns about unmapped target properties. Set unmappedTargetPolicy = ReportingPolicy.ERROR so a forgotten field fails the build.
  • With Lombok, add lombok-mapstruct-binding and list Lombok's processor before MapStruct's. With records, MapStruct uses the canonical constructor.

Option 3: ModelMapper (reflection at run time)

ModelMapper maps by convention at run time. You write one line and it matches properties by name, including nested ones such as author.name to authorName:

Java
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

BookResponse dto = mapper.map(book, BookResponse.class);
List<BookResponse> dtos = mapper.map(books, new TypeToken<List<BookResponse>>() {}.getType());

It is quick to start and needs no annotation processor. The cost is that everything happens by reflection and guessing. A renamed field does not fail to compile; it just becomes null. The default "standard" matching strategy can also match the wrong property when two names are alike (authorName could come from author.name or from name). Use STRICT, call mapper.validate() in a test, and register explicit typeMap rules for anything tricky.

The silent-null pitfall, reproduced

This stand-in is a tiny reflective mapper that copies record components by name. It shows exactly what goes wrong when a name changes, and how a validate()-style check catches it. It is not ModelMapper; it only reproduces the behavior that matters.

Java Why name-based mapping needs validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The mapper ran without complaint and produced a DTO with name=null. In production that means an API field that is quietly empty. MapStruct would have reported Unmapped target property: "name" at compile time; with ModelMapper you must ask for the check yourself.

Choosing between them

By hand MapStruct ModelMapper
When errors appear Compile time Compile time Run time (or never)
Speed Fastest Same as by hand Slower (reflection)
Boilerplate Most Little Least
Debugging Trivial Read the generated class Harder
Custom logic Plain Java @Named, default methods Converters, type maps

A good default is MapStruct for mid-size and large projects, by hand for small ones, and ModelMapper only when you accept the run-time trade-off. Whichever you choose, keep these habits:

  • Map in the service or controller layer, not in the entity. Entities should not know about DTOs.
  • Avoid mapping lazy collections you did not load. Fetch what the DTO needs in the query (a join fetch or a projection, see Spring Data JPA in Boot) before mapping, inside the transaction.
  • Do not map in both directions "for symmetry". Request-to-entity and entity-to-response are different jobs with different ignored fields.
  • Test the mapper. One unit test per mapper method, with every field set to a distinct value, catches swapped and forgotten fields.
  • For updates, decide what null means. In a PATCH, "field absent" and "field set to null" are different. Records cannot tell them apart, so many teams use Optional fields, a Map, or JSON Merge Patch.

Updating in place

Java Partial update that ignores null fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the limit: with "ignore nulls", a client can no longer clear the subtitle. If that matters, model the patch explicitly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main reason to return DTOs instead of JPA entities from a controller?

    Entities describe storage. A DTO is a deliberate public contract, which prevents leaks, lazy-loading surprises and accidental coupling.
  2. 2. How does MapStruct differ from ModelMapper?

    MapStruct is an annotation processor, so errors show up at build time and there is no reflection cost. ModelMapper discovers properties while running.
  3. 3. In the reflective mapper above, the DTO field name ended up null. What is the lesson?

    Nothing matched the name, so nothing was copied and nothing complained. Use compile-time checks (MapStruct with an error policy) or ModelMapper's validate().
  4. 4. What does @MappingTarget do in a MapStruct method?

    It is the way to apply a patch to an already loaded entity, usually together with a strategy for null source values.
  5. 5. Where should mapping code live?

    Keeping mapping outside the entity keeps persistence classes free of API concerns and makes the mapper easy to unit test.

Summary

  • DTOs are the public contract of your API; entities are your storage model. Keep them separate, and use different request and response DTOs.
  • A hand-written mapper is explicit and safe; MapStruct generates the same kind of code at compile time and fails the build on forgotten fields; ModelMapper maps by reflection and needs STRICT matching plus a validate() test.
  • Map nested objects and lists with uses, a collection method or small helper methods, and apply business formatting in the mapper.
  • Update existing objects with @MappingTarget, and decide deliberately what null means in a patch.
  • Fetch the data you need before mapping so lazy associations do not surprise you.

Next: Filters and Interceptors.