BBackend CourseLeroy Labs
0/0
Search the course

Object mapping with MapStruct

Compile-time generated mappers. @Mapping, expressions, @MappingTarget for updates, and how it compares to manual mapping and ModelMapper.

● beginnerSpring-Boot-StoreHostel-Web-AppReport-Manager-2

The concept

MapStruct is an annotation processor. You write an interface, and at compile time it generates a plain Java class with getter and setter calls. There is no reflection at runtime, so it is as fast as handwritten code, and mistakes show up as compile errors.

@Mapper(componentModel = "spring")
public interface ProductMapper {
    @Mapping(source = "category.id", target = "categoryId")   // nested -> flat
    ProductDto toDto(Product product);

    @Mapping(target = "id", ignore = true)                    // never let clients set id
    Product toEntity(ProductDto dto);

    @Mapping(target = "id", ignore = true)
    void update(ProductDto dto, @MappingTarget Product product); // in-place update
}

The generated code looks roughly like this:

@Component
public class ProductMapperImpl implements ProductMapper {
    public ProductDto toDto(Product p) {
        if (p == null) return null;
        ProductDto dto = new ProductDto();
        dto.setId(p.getId());
        dto.setName(p.getName());
        dto.setCategoryId(p.getCategory() != null ? p.getCategory().getId() : null);
        return dto;
    }
}

In your projects

Spring-Boot-Storemappers/CartMapper.java · UserMapper.java · ProductMapper.java

Store uses MapStruct expressions to fill computed fields, and @MappingTarget for PUT updates:

@Mapping(target = "totalPrice", expression = "java(cart.getTotalPrice())")
CartDto toDto(Cart cart);

void updateUser(UpdateUserRequest request, @MappingTarget User user);

getTotalPrice() is domain logic on the Cart entity, so the mapper calls it rather than recomputing the total.

Hostel-Web-Appmodule/*/mapper/*Mapper.java

Hostel has one mapper per module (BookingMapper, HostelMapper, …). Services return DTOs that are already mapped, so controllers never touch entities.

Report-Manager-2module/account/application/AccountMapper.java

RM uses MapStruct across about 400 files. In a codebase that size, compile-time checks catch DTO and entity drift that would otherwise reach production.

Alternatives

Tool Pros Cons
MapStruct (yours) Fast, compile-time checked, debuggable generated code Annotation-processor setup; complex logic gets awkward
Manual mapping (static from() methods) Zero magic, full control Boilerplate; easy to forget a field
ModelMapper / Dozer Zero config Reflection is slow, and mistakes only appear at runtime
Records with a from(entity) factory Simple and idiomatic Fine for small projects
Spring Data projections Skips the entity entirely Read-only
  • Annotation processing order. Lombok has to run before MapStruct. Projects add lombok-mapstruct-binding for this.
  • componentModel = "spring" makes the mapper an injectable bean.
  • Null handling on updates. nullValuePropertyMappingStrategy = IGNORE turns a PUT into PATCH-like behaviour, where nulls don’t overwrite existing values.
  • Mapping collections. MapStruct generates the loops for you, but mapping a lazy collection still triggers a query. Fetch what you’ll map (see the N+1 lesson).

Check yourself

1. When does MapStruct detect a mapping mistake?
2. What does @MappingTarget do?