MapStruct helps you copy data between objects easily without writing boring code. It saves time and avoids mistakes.
MapStruct for automatic mapping in Spring Boot
@Mapper
public interface YourMapper {
TargetObject toTarget(SourceObject source);
}@Mapper tells MapStruct to create the mapping code automatically.
The method defines how to convert from one object to another.
@Mapper
public interface UserMapper {
UserDTO toUserDTO(User user);
}@Mapper
public interface CarMapper {
CarDTO toCarDTO(Car car);
Car toCar(CarDTO carDTO);
}componentModel = "spring" lets Spring manage the mapper as a bean.@Mapper(componentModel = "spring")
public interface EmployeeMapper {
EmployeeDTO toEmployeeDTO(Employee employee);
}This Spring Boot example shows how MapStruct automatically copies data from a User object to a UserDTO object. The mapper is injected by Spring and used in the main application.
package com.example.demo.mapper; import org.mapstruct.Mapper; import com.example.demo.model.User; import com.example.demo.dto.UserDTO; @Mapper(componentModel = "spring") public interface UserMapper { UserDTO toUserDTO(User user); } // User.java package com.example.demo.model; public class User { private String name; private int age; public User() {} public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } } // UserDTO.java package com.example.demo.dto; public class UserDTO { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } } // DemoApplication.java package com.example.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.beans.factory.annotation.Autowired; import com.example.demo.mapper.UserMapper; import com.example.demo.model.User; import com.example.demo.dto.UserDTO; @SpringBootApplication public class DemoApplication implements CommandLineRunner { @Autowired private UserMapper userMapper; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) throws Exception { User user = new User("Alice", 30); UserDTO userDTO = userMapper.toUserDTO(user); System.out.println("UserDTO name: " + userDTO.getName()); System.out.println("UserDTO age: " + userDTO.getAge()); } }
MapStruct generates code at compile time, so your app runs fast.
Make sure your source and target objects have matching field names or use annotations to customize.
Use componentModel = "spring" to let Spring inject the mapper easily.
MapStruct automatically copies data between objects to save time and avoid errors.
It works by defining interfaces with @Mapper and methods for conversion.
Spring Boot can manage mappers as beans for easy use in your app.
Practice
MapStruct in a Spring Boot application?Solution
Step 1: Understand MapStruct's role
MapStruct is a tool designed to copy data between objects automatically, reducing manual coding.Step 2: Compare with other options
Options A, B, and C relate to other parts of Spring Boot, not object mapping.Final Answer:
To automatically map data between different object types -> Option CQuick Check:
MapStruct = automatic object mapping [OK]
- Confusing MapStruct with database or web handling
- Thinking MapStruct creates UI components
- Assuming MapStruct manages HTTP requests
Solution
Step 1: Identify the correct MapStruct annotation
MapStruct uses@Mapperto mark interfaces for automatic mapping generation.Step 2: Understand Spring stereotypes
@Component, @Service, and @Repository are Spring annotations for beans but not for MapStruct mapping.Final Answer:
@Mapper -> Option BQuick Check:
MapStruct interface = @Mapper [OK]
- Using @Component instead of @Mapper
- Confusing Spring stereotypes with MapStruct annotations
- Omitting the @Mapper annotation
@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)?Solution
Step 1: Understand componentModel = "spring"
This setting tells MapStruct to generate a Spring bean implementation automatically.Step 2: Effect of calling toDto(user)
The generated implementation copies matching fields from User to UserDto automatically.Final Answer:
It converts the User object to a UserDto automatically -> Option AQuick Check:
componentModel spring = auto bean + mapping [OK]
- Thinking manual implementation is needed
- Assuming it returns original object
- Expecting runtime errors without implementation
@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?Solution
Step 1: Check mapper registration in Spring context
WithoutcomponentModel = "spring", MapStruct does not create a Spring bean for the mapper.Step 2: Understand injection failure
Spring cannot inject the mapper because it is not registered as a bean, causing an error.Final Answer:
Missing componentModel = "spring" to register mapper as a Spring bean -> Option AQuick Check:
Missing spring componentModel = no bean injection [OK]
- Thinking method name causes error
- Believing MapStruct can't map certain classes
- Confusing interface with class requirement
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?Solution
Step 1: Identify ignoring a field in MapStruct
To ignore a field during mapping, use@Mapping(target = "fieldName", ignore = true)on the method.Step 2: Check componentModel for Spring bean
UsingcomponentModel = "spring"allows Spring to manage the mapper bean automatically.Final Answer:
@Mapper(componentModel = "spring") public interface EmployeeMapper { @Mapping(target = "department", ignore = true) EmployeeDto toDto(Employee employee); } -> Option DQuick Check:
Ignore field with @Mapping(target, ignore=true) + spring bean [OK]
- Not using @Mapping to ignore fields
- Forgetting componentModel = "spring" for bean
- Incorrectly mapping ignored fields
Ready to prove it?
Pass the test and this pattern moves unknown
