Bird
Raised Fist0
Spring Bootframework~10 mins

MapStruct for automatic mapping in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - MapStruct for automatic mapping
Define Source Class
Define Target Class
Create Mapper Interface
MapStruct Generates Implementation
Use Mapper to Convert Objects
Get Mapped Target Object
MapStruct automatically creates code to convert one object type to another using a mapper interface.
Execution Sample
Spring Boot
public interface CarMapper {
    CarDto carToCarDto(Car car);
}
Defines a mapper interface method to convert a Car object to a CarDto object.
Execution Table
StepActionInput ObjectMapper Method CalledOutput Object
1Create Car objectCar{make='Toyota', year=2020}N/AN/A
2Call mapper method carToCarDtoCar{make='Toyota', year=2020}carToCarDtoN/A
3MapStruct generates CarDtoN/AcarToCarDtoCarDto{make='Toyota', year=2020}
4Return mapped CarDtoN/AcarToCarDtoCarDto{make='Toyota', year=2020}
5Use CarDto objectN/AN/ACarDto{make='Toyota', year=2020}
6End of mapping processN/AN/AN/A
💡 Mapping ends after CarDto object is returned from mapper method.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
carnullCar{make='Toyota', year=2020}Car{make='Toyota', year=2020}Car{make='Toyota', year=2020}Car{make='Toyota', year=2020}
carDtonullnullCarDto{make='Toyota', year=2020}CarDto{make='Toyota', year=2020}CarDto{make='Toyota', year=2020}
Key Moments - 3 Insights
Why don't we see the implementation code of the mapper method?
MapStruct generates the implementation automatically at compile time, so you only write the interface method (see execution_table step 3).
How does MapStruct know which fields to map?
MapStruct matches fields by name and type between source and target classes, so fields with the same name are mapped automatically (refer to variable_tracker showing matching fields).
What happens if source and target fields have different names?
You can configure MapStruct with annotations to map fields with different names, but by default only matching names are mapped (not shown in this simple trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of carDto after step 3?
ACarDto{make='Toyota', year=2020}
Bnull
CCar{make='Toyota', year=2020}
DN/A
💡 Hint
Check the 'Output Object' column at step 3 in the execution_table.
At which step does MapStruct generate the implementation code?
AStep 1
BStep 3
CStep 2
DStep 5
💡 Hint
Look for the step mentioning 'MapStruct generates CarDto' in the execution_table.
If the Car object had a field not present in CarDto, what would happen by default?
AMapping would fail with error
BMapStruct would map it anyway
CMapStruct would ignore that field
DThe field would be set to null in CarDto
💡 Hint
Recall that MapStruct maps matching fields by name; unmatched fields are ignored by default.
Concept Snapshot
MapStruct automates object mapping in Spring Boot.
Define source and target classes.
Create a mapper interface with mapping methods.
MapStruct generates implementation at compile time.
Use mapper methods to convert objects easily.
Matches fields by name automatically.
Full Transcript
MapStruct is a tool used in Spring Boot to automatically convert one object type to another. You start by defining your source and target classes, for example, Car and CarDto. Then you create a mapper interface with a method like carToCarDto. MapStruct generates the actual code behind the scenes during compilation. When you call the mapper method with a Car object, it returns a CarDto with matching fields copied over. This process saves you from writing repetitive conversion code. Fields with the same name and type are mapped automatically. If fields differ, you can configure mappings with annotations. The execution table shows the step-by-step flow from creating the Car object, calling the mapper, MapStruct generating the CarDto, and returning it for use. Variables track how car and carDto change during the process. Common confusions include why you don't see the implementation code (it's generated), how fields are matched (by name), and what happens with unmatched fields (ignored by default). The visual quiz tests understanding of these steps and behaviors.

Practice

(1/5)
1. What is the main purpose of using MapStruct in a Spring Boot application?
easy
A. To create user interface components
B. To manage database connections
C. To automatically map data between different object types
D. To handle HTTP requests and responses

Solution

  1. Step 1: Understand MapStruct's role

    MapStruct is a tool designed to copy data between objects automatically, reducing manual coding.
  2. Step 2: Compare with other options

    Options A, B, and C relate to other parts of Spring Boot, not object mapping.
  3. Final Answer:

    To automatically map data between different object types -> Option C
  4. Quick Check:

    MapStruct = automatic object mapping [OK]
Hint: MapStruct = automatic copying between objects [OK]
Common Mistakes:
  • Confusing MapStruct with database or web handling
  • Thinking MapStruct creates UI components
  • Assuming MapStruct manages HTTP requests
2. Which annotation is used to define a MapStruct mapper interface in Spring Boot?
easy
A. @Component
B. @Mapper
C. @Service
D. @Repository

Solution

  1. Step 1: Identify the correct MapStruct annotation

    MapStruct uses @Mapper to mark interfaces for automatic mapping generation.
  2. Step 2: Understand Spring stereotypes

    @Component, @Service, and @Repository are Spring annotations for beans but not for MapStruct mapping.
  3. Final Answer:

    @Mapper -> Option B
  4. Quick Check:

    MapStruct interface = @Mapper [OK]
Hint: MapStruct interfaces use @Mapper annotation [OK]
Common Mistakes:
  • Using @Component instead of @Mapper
  • Confusing Spring stereotypes with MapStruct annotations
  • Omitting the @Mapper annotation
3. Given the following mapper interface:
@Mapper(componentModel = "spring")
public interface UserMapper {
    UserDto toDto(User user);
}

What happens when you inject UserMapper in a Spring Boot service and call toDto(user)?
medium
A. It converts the User object to a UserDto automatically
B. It throws a NullPointerException because no implementation exists
C. It returns the original User object without changes
D. It requires manual implementation to work

Solution

  1. Step 1: Understand componentModel = "spring"

    This setting tells MapStruct to generate a Spring bean implementation automatically.
  2. Step 2: Effect of calling toDto(user)

    The generated implementation copies matching fields from User to UserDto automatically.
  3. Final Answer:

    It converts the User object to a UserDto automatically -> Option A
  4. Quick Check:

    componentModel spring = auto bean + mapping [OK]
Hint: componentModel spring means auto Spring bean mapper [OK]
Common Mistakes:
  • Thinking manual implementation is needed
  • Assuming it returns original object
  • Expecting runtime errors without implementation
4. Consider this mapper interface:
@Mapper
public interface ProductMapper {
    ProductDto toDto(Product product);
}

When you try to inject ProductMapper in a Spring Boot service, you get an error. What is the likely cause?
medium
A. Missing componentModel = "spring" to register mapper as a Spring bean
B. The method name toDto is invalid
C. MapStruct does not support mapping Product to ProductDto
D. The interface must be a class, not an interface

Solution

  1. Step 1: Check mapper registration in Spring context

    Without componentModel = "spring", MapStruct does not create a Spring bean for the mapper.
  2. Step 2: Understand injection failure

    Spring cannot inject the mapper because it is not registered as a bean, causing an error.
  3. Final Answer:

    Missing componentModel = "spring" to register mapper as a Spring bean -> Option A
  4. Quick Check:

    Missing spring componentModel = no bean injection [OK]
Hint: Add componentModel spring to enable Spring bean injection [OK]
Common Mistakes:
  • Thinking method name causes error
  • Believing MapStruct can't map certain classes
  • Confusing interface with class requirement
5. You have two classes:
public class Employee {
    private String name;
    private int age;
    private String department;
    // getters and setters
}

public class EmployeeDto {
    private String name;
    private int age;
    // getters and setters
}

You want to map Employee to EmployeeDto using MapStruct but ignore the department field. Which mapper method signature and annotation is correct?
hard
A. @Mapper public interface EmployeeMapper { EmployeeDto toDto(Employee employee); }
B. @Mapper(componentModel = "spring") public interface EmployeeMapper { EmployeeDto toDto(Employee employee); }
C. @Mapper public interface EmployeeMapper { @Mapping(source = "department", target = "department") EmployeeDto toDto(Employee employee); }
D. @Mapper(componentModel = "spring") public interface EmployeeMapper { @Mapping(target = "department", ignore = true) EmployeeDto toDto(Employee employee); }

Solution

  1. Step 1: Identify ignoring a field in MapStruct

    To ignore a field during mapping, use @Mapping(target = "fieldName", ignore = true) on the method.
  2. Step 2: Check componentModel for Spring bean

    Using componentModel = "spring" allows Spring to manage the mapper bean automatically.
  3. Final Answer:

    @Mapper(componentModel = "spring") public interface EmployeeMapper { @Mapping(target = "department", ignore = true) EmployeeDto toDto(Employee employee); } -> Option D
  4. Quick Check:

    Ignore field with @Mapping(target, ignore=true) + spring bean [OK]
Hint: Use @Mapping(target, ignore=true) to skip fields [OK]
Common Mistakes:
  • Not using @Mapping to ignore fields
  • Forgetting componentModel = "spring" for bean
  • Incorrectly mapping ignored fields